public void quitSynchronously() { state = State.DONE; cameraManager.stopPreview(); Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit); quit.sendToTarget(); try { // Wait at most half a second; should be enough time, and onPause() will timeout quickly decodeThread.join(500L); } catch (InterruptedException e) { // continue } // Be absolutely sure we don't send any queued up messages removeMessages(R.id.decode_succeeded); removeMessages(R.id.decode_failed); }
@SuppressLint("DrawAllocation") @Override public void onDraw(Canvas canvas) { if (cameraManager == null) { return; // not ready yet, early draw before done configuring } Rect frame = cameraManager.getFramingRect(); Rect previewFrame = cameraManager.getFramingRectInPreview(); if (frame == null || previewFrame == null) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); // Draw the exterior (i.e. outside the framing rect) darkened // Draw a two pixel solid black border inside the framing rect int widthBorder = getResources().getDimensionPixelSize(R.dimen.width_margin_camera); paint.setColor(getResources().getColor(R.color.colorPrimary)); canvas.drawRect(frame.left, frame.top, frame.right + widthBorder/2, frame.top + widthBorder, paint); canvas.drawRect(frame.left, frame.top + widthBorder, frame.left + widthBorder, frame.bottom - widthBorder/2, paint); canvas.drawRect(frame.right - widthBorder/2, frame.top, frame.right + widthBorder/2, frame.bottom - widthBorder/2, paint); canvas.drawRect(frame.left, frame.bottom - widthBorder/2, frame.right + widthBorder/2, frame.bottom + widthBorder/2, paint); }
private MediaPlayer buildMediaPlayer(Context activity,modes mode) { MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnErrorListener(this); try { AssetFileDescriptor file; if(mode==modes.SINGLE) file = activity.getResources().openRawResourceFd(R.raw.beep); else file = activity.getResources().openRawResourceFd(R.raw.triplebeep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); } finally { file.close(); } mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); return mediaPlayer; } catch (IOException ioe) { Log.w(TAG, ioe); mediaPlayer.release(); return null; } }
@Override public View getView(int position, View view, ViewGroup viewGroup) { SearchBookContentsListItem listItem; if (view == null) { LayoutInflater factory = LayoutInflater.from(getContext()); listItem = (SearchBookContentsListItem) factory.inflate(R.layout.search_book_contents_list_item, viewGroup, false); } else { if (view instanceof SearchBookContentsListItem) { listItem = (SearchBookContentsListItem) view; } else { return view; } } SearchBookContentsResult result = getItem(position); listItem.set(result); return listItem; }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private void launchSearch() { String query = queryTextView.getText().toString(); if (query != null && !query.isEmpty()) { AsyncTask<?, ?, ?> oldTask = networkTask; if (oldTask != null) { oldTask.cancel(true); } networkTask = new NetworkTask(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, query, isbn); } else { networkTask.execute(query, isbn); } headerView.setText(R.string.msg_sbc_searching_book); resultListView.setAdapter(null); queryTextView.setEnabled(false); queryButton.setEnabled(false); } }
@Override public View getView(int index, View view, ViewGroup viewGroup) { View layout; if (view instanceof LinearLayout) { layout = view; } else { LayoutInflater factory = LayoutInflater.from(context); layout = factory.inflate(R.layout.bookmark_picker_list_item, viewGroup, false); } if (!cursor.isClosed()) { cursor.moveToPosition(index); CharSequence title = cursor.getString(BookmarkPickerActivity.TITLE_COLUMN); ((TextView) layout.findViewById(R.id.bookmark_title)).setText(title); CharSequence url = cursor.getString(BookmarkPickerActivity.URL_COLUMN); ((TextView) layout.findViewById(R.id.bookmark_url)).setText(url); } // Otherwise... just don't update as the object is shutting down return layout; }
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_share: share(); return true; case R.id.menu_encode: Intent intent = getIntent(); if (intent == null) { return false; } intent.putExtra(USE_VCARD_KEY, !qrCodeEncoder.isUseVCard()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); return true; default: return false; } }
private void encodeQRCodeContents(AddressBookParsedResult contact) { ContactEncoder encoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder(); String[] encoded = encoder.encode(toIterable(contact.getNames()), contact.getOrg(), toIterable(contact.getAddresses()), toIterable(contact.getPhoneNumbers()), toIterable(contact.getEmails()), toIterable(contact.getURLs()), null); // Make sure we've encoded at least one field. if (!encoded[1].isEmpty()) { contents = encoded[0]; displayContents = encoded[1]; title = activity.getString(R.string.contents_contact); } }
private void handleSearchResults(JSONObject json) { try { int count = json.getInt("number_of_results"); headerView.setText(getString(R.string.msg_sbc_results) + " : " + count); if (count > 0) { JSONArray results = json.getJSONArray("search_results"); SearchBookContentsResult.setQuery(queryTextView.getText().toString()); List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(count); for (int x = 0; x < count; x++) { items.add(parseResult(results.getJSONObject(x))); } resultListView.setOnItemClickListener(new BrowseBookListener(SearchBookContentsActivity.this, items)); resultListView.setAdapter(new SearchBookContentsAdapter(SearchBookContentsActivity.this, items)); } else { String searchable = json.optString("searchable"); if ("false".equals(searchable)) { headerView.setText(R.string.msg_sbc_book_not_searchable); } resultListView.setAdapter(null); } } catch (JSONException e) { Log.w(TAG, "Bad JSON from book search", e); resultListView.setAdapter(null); headerView.setText(R.string.msg_sbc_failed); } }
private void encodeQRCodeContents(AddressBookParsedResult contact) { ContactEncoder encoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder(); String[] encoded = encoder.encode(toList(contact.getNames()), contact.getOrg(), toList(contact.getAddresses()), toList(contact.getPhoneNumbers()), null, toList(contact.getEmails()), toList(contact.getURLs()), null); // Make sure we've encoded at least one field. if (!encoded[1].isEmpty()) { contents = encoded[0]; displayContents = encoded[1]; title = activity.getString(R.string.contents_contact); } }
@Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_share) { share(); return true; } else if (itemId == R.id.menu_encode) { Intent intent = getIntent(); if (intent == null) { return false; } intent.putExtra(USE_VCARD_KEY, !qrCodeEncoder.isUseVCard()); startActivity(intent); finish(); return true; } else { return false; } }
@Override protected void onPostExecute(final List<AppInfo> results) { ListAdapter listAdapter = new ArrayAdapter<AppInfo>(activity, R.layout.app_picker_list_item, R.id.app_picker_list_item_label, results) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); Drawable icon = results.get(position).getIcon(); if (icon != null) { ((ImageView) view.findViewById(R.id.app_picker_list_item_icon)).setImageDrawable(icon); } return view; } }; activity.setListAdapter(listAdapter); }
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.share); findViewById(R.id.share_contact_button).setOnClickListener(contactListener); if (Build.VERSION.SDK_INT >= 23) { // Marshmallow / 6.0 // Can't access bookmarks in 6.0+ findViewById(R.id.share_bookmark_button).setEnabled(false); } else { findViewById(R.id.share_bookmark_button).setOnClickListener(bookmarkListener); } findViewById(R.id.share_app_button).setOnClickListener(appListener); clipboardButton = findViewById(R.id.share_clipboard_button); clipboardButton.setOnClickListener(clipboardListener); findViewById(R.id.share_text_view).setOnKeyListener(textListener); }
@Override public void handleMessage(Message message) { if (message.what == R.id.restart_preview) { restartPreviewAndDecode(); } else if (message.what == R.id.decode_succeeded) { state = State.SUCCESS; Bundle bundle = message.getData(); Bitmap barcode = null; float scaleFactor = 1.0f; if (bundle != null) { byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP); if (compressedBitmap != null) { barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null); // Mutable copy: barcode = barcode.copy(Bitmap.Config.ARGB_8888, true); } scaleFactor = bundle.getFloat(DecodeThread.BARCODE_SCALED_FACTOR); } activity.handleDecode((Result) message.obj, barcode, scaleFactor); } else if (message.what == R.id.decode_failed) {// We're decoding as fast as possible, so when one decode fails, start another. state = State.PREVIEW; cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode); } else if (message.what == R.id.return_scan_result) { activity.getActivity().setResult(Activity.RESULT_OK, (Intent) message.obj); activity.getActivity().finish(); } }
private void restartPreviewAndDecode() { if (state == State.SUCCESS) { state = State.PREVIEW; cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode); activity.drawViewfinder(); } }
public ViewfinderView(Context context, AttributeSet attrs) { super(context, attrs); // Initialize these once for performance rather than calling them every time in onDraw(). paint = new Paint(Paint.ANTI_ALIAS_FLAG); Resources resources = getResources(); maskColor = resources.getColor(R.color.colorPrimary); scannerAlpha = 0; possibleResultPoints = new ArrayList<>(5); lastPossibleResultPoints = null; }
@Override public void handleMessage(Message message) { if (!running) { return; } if (message.what == R.id.decode) { decode((byte[]) message.obj, message.arg1, message.arg2); } else if (message.what == R.id.quit) { running = false; Looper.myLooper().quit(); } }
private void showErrorMessage(int message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.setPositiveButton(R.string.button_ok, new FinishListener(this)); builder.setOnCancelListener(new FinishListener(this)); builder.show(); }
@Override protected void onPostExecute(JSONObject result) { if (result == null) { headerView.setText(R.string.msg_sbc_failed); } else { handleSearchResults(result); } queryTextView.setEnabled(true); queryTextView.selectAll(); queryButton.setEnabled(true); }
final void sendMMSFromUri(String uri, String subject, String body) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri)); // The Messaging app needs to see a valid subject or else it will treat this an an SMS. if (subject == null || subject.isEmpty()) { putExtra(intent, "subject", activity.getString(R.string.msg_default_mms_subject)); } else { putExtra(intent, "subject", subject); } putExtra(intent, "sms_body", body); intent.putExtra("compose_mode", true); launchIntent(intent); }
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.share); findViewById(R.id.share_contact_button).setOnClickListener(contactListener); findViewById(R.id.share_bookmark_button).setOnClickListener(bookmarkListener); findViewById(R.id.share_app_button).setOnClickListener(appListener); clipboardButton = findViewById(R.id.share_clipboard_button); clipboardButton.setOnClickListener(clipboardListener); findViewById(R.id.share_text_view).setOnKeyListener(textListener); }
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.encode, menu); boolean useVcard = qrCodeEncoder != null && qrCodeEncoder.isUseVCard(); int encodeNameResource = useVcard ? R.string.menu_encode_mecard : R.string.menu_encode_vcard; MenuItem encodeItem = menu.findItem(R.id.menu_encode); encodeItem.setTitle(encodeNameResource); Intent intent = getIntent(); if (intent != null) { String type = intent.getStringExtra(Intents.Encode.TYPE); encodeItem.setVisible(Contents.Type.CONTACT.equals(type)); } return super.onCreateOptionsMenu(menu); }
@Override public View getView(int position, View view, ViewGroup viewGroup) { View layout; if (view instanceof LinearLayout) { layout = view; } else { LayoutInflater factory = LayoutInflater.from(activity); layout = factory.inflate(R.layout.history_list_item, viewGroup, false); } HistoryItem item = getItem(position); Result result = item.getResult(); CharSequence title; CharSequence detail; if (result != null) { title = result.getText(); detail = item.getDisplayAndDetails(); } else { Resources resources = getContext().getResources(); title = resources.getString(R.string.history_empty); detail = resources.getString(R.string.history_empty_detail); } ((TextView) layout.findViewById(R.id.history_title)).setText(title); ((TextView) layout.findViewById(R.id.history_detail)).setText(detail); return layout; }
private boolean encodeContentsFromZXingIntent(Intent intent) { // Default to QR_CODE if no format given. String formatString = intent.getStringExtra(Intents.Encode.FORMAT); format = null; if (formatString != null) { try { format = BarcodeFormat.valueOf(formatString); } catch (IllegalArgumentException iae) { // Ignore it then } } if (format == null || format == BarcodeFormat.QR_CODE) { String type = intent.getStringExtra(Intents.Encode.TYPE); if (type == null || type.isEmpty()) { return false; } this.format = BarcodeFormat.QR_CODE; encodeQRCodeContents(intent, type); } else { String data = intent.getStringExtra(Intents.Encode.DATA); if (data != null && !data.isEmpty()) { contents = data; displayContents = data; title = activity.getString(R.string.contents_text); } } return contents != null && !contents.isEmpty(); }
@Override public boolean onCreateOptionsMenu(Menu menu) { if (historyManager.hasHistoryItems()) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.history, menu); } return super.onCreateOptionsMenu(menu); }
final void sendMMSFromUri(String uri, String subject, String body) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri)); // The Messaging app needs to see a valid subject or else it will treat // this an an SMS. if (subject == null || subject.isEmpty()) { putExtra(intent, "subject", activity.getString(R.string.msg_default_mms_subject)); } else { putExtra(intent, "subject", subject); } putExtra(intent, "sms_body", body); intent.putExtra("compose_mode", true); launchIntent(intent); }
/** * Like {@link #rawLaunchIntent(Intent)} but will show a user dialog if * nothing is available to handle. */ final void launchIntent(Intent intent) { try { rawLaunchIntent(intent); } catch (ActivityNotFoundException ignored) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.app_name); builder.setMessage(R.string.msg_intent_failed); builder.setPositiveButton(R.string.button_ok, null); builder.show(); } }
private void encodeFromTextExtras(Intent intent) throws WriterException { // Notice: Google Maps shares both URL and details in one text, bummer! String theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_TEXT)); if (theContents == null) { theContents = ContactEncoder.trim(intent.getStringExtra("android.intent.extra.HTML_TEXT")); // Intent.EXTRA_HTML_TEXT if (theContents == null) { theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_SUBJECT)); if (theContents == null) { String[] emails = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); if (emails != null) { theContents = ContactEncoder.trim(emails[0]); } else { theContents = "?"; } } } } // Trim text to avoid URL breaking. if (theContents == null || theContents.isEmpty()) { throw new WriterException("Empty EXTRA_TEXT"); } contents = theContents; // We only do QR code. format = BarcodeFormat.QR_CODE; if (intent.hasExtra(Intent.EXTRA_SUBJECT)) { displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT); } else if (intent.hasExtra(Intent.EXTRA_TITLE)) { displayContents = intent.getStringExtra(Intent.EXTRA_TITLE); } else { displayContents = contents; } title = activity.getString(R.string.contents_text); }
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position; if (position >= adapter.getCount() || adapter.getItem(position).getResult() != null) { menu.add(Menu.NONE, position, position, R.string.history_clear_one_history_text); } // else it's just that dummy "Empty" message }