2 * Copyright (C) 2008 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.client.android;
19 import android.util.TypedValue;
20 import android.widget.Toast;
21 import com.google.zxing.BarcodeFormat;
22 import com.google.zxing.Result;
23 import com.google.zxing.ResultPoint;
24 import com.google.zxing.client.android.camera.CameraManager;
25 import com.google.zxing.client.android.history.HistoryManager;
26 import com.google.zxing.client.android.result.ResultButtonListener;
27 import com.google.zxing.client.android.result.ResultHandler;
28 import com.google.zxing.client.android.result.ResultHandlerFactory;
29 import com.google.zxing.client.android.share.ShareActivity;
31 import android.app.Activity;
32 import android.app.AlertDialog;
33 import android.content.DialogInterface;
34 import android.content.Intent;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageInfo;
37 import android.content.pm.PackageManager;
38 import android.content.res.AssetFileDescriptor;
39 import android.content.res.Configuration;
40 import android.graphics.Bitmap;
41 import android.graphics.Canvas;
42 import android.graphics.Paint;
43 import android.graphics.Rect;
44 import android.media.AudioManager;
45 import android.media.MediaPlayer;
46 import android.media.MediaPlayer.OnCompletionListener;
47 import android.net.Uri;
48 import android.os.Bundle;
49 import android.os.Handler;
50 import android.os.Message;
51 import android.os.Vibrator;
52 import android.preference.PreferenceManager;
53 import android.text.ClipboardManager;
54 import android.util.Log;
55 import android.view.KeyEvent;
56 import android.view.Menu;
57 import android.view.MenuItem;
58 import android.view.SurfaceHolder;
59 import android.view.SurfaceView;
60 import android.view.View;
61 import android.view.ViewGroup;
62 import android.view.Window;
63 import android.view.WindowManager;
64 import android.widget.ImageView;
65 import android.widget.TextView;
67 import java.io.IOException;
68 import java.text.DateFormat;
69 import java.util.Arrays;
70 import java.util.List;
71 import java.util.Date;
72 import java.util.Vector;
73 import java.util.regex.Pattern;
76 * The barcode reader activity itself. This is loosely based on the CameraPreview
77 * example included in the Android SDK.
79 * @author dswitkin@google.com (Daniel Switkin)
81 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
83 private static final String TAG = CaptureActivity.class.getSimpleName();
85 private static final Pattern COMMA_PATTERN = Pattern.compile(",");
87 private static final int SHARE_ID = Menu.FIRST;
88 private static final int HISTORY_ID = Menu.FIRST + 1;
89 private static final int SETTINGS_ID = Menu.FIRST + 2;
90 private static final int HELP_ID = Menu.FIRST + 3;
91 private static final int ABOUT_ID = Menu.FIRST + 4;
93 private static final long INTENT_RESULT_DURATION = 1500L;
94 private static final float BEEP_VOLUME = 0.10f;
95 private static final long VIBRATE_DURATION = 200L;
97 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
98 private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
99 private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
100 private static final String ZXING_URL = "http://zxing.appspot.com/scan";
101 private static final String RETURN_CODE_PLACEHOLDER = "{CODE}";
102 private static final String RETURN_URL_PARAM = "ret";
104 static final Vector<BarcodeFormat> PRODUCT_FORMATS;
105 static final Vector<BarcodeFormat> ONE_D_FORMATS;
106 static final Vector<BarcodeFormat> QR_CODE_FORMATS;
107 static final Vector<BarcodeFormat> ALL_FORMATS;
110 PRODUCT_FORMATS = new Vector<BarcodeFormat>(5);
111 PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
112 PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
113 PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
114 PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
115 PRODUCT_FORMATS.add(BarcodeFormat.RSS14);
116 ONE_D_FORMATS = new Vector<BarcodeFormat>(PRODUCT_FORMATS.size() + 3);
117 ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
118 ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
119 ONE_D_FORMATS.add(BarcodeFormat.CODE_93);
120 ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
121 ONE_D_FORMATS.add(BarcodeFormat.ITF);
122 QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
123 QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
124 ALL_FORMATS = new Vector<BarcodeFormat>(ONE_D_FORMATS.size() + QR_CODE_FORMATS.size());
125 ALL_FORMATS.addAll(ONE_D_FORMATS);
126 ALL_FORMATS.addAll(QR_CODE_FORMATS);
129 private enum Source {
136 private CaptureActivityHandler handler;
138 private ViewfinderView viewfinderView;
139 private View statusView;
140 private View resultView;
141 private MediaPlayer mediaPlayer;
142 private Result lastResult;
143 private boolean hasSurface;
144 private boolean playBeep;
145 private boolean vibrate;
146 private boolean copyToClipboard;
147 private Source source;
148 private String sourceUrl;
149 private String returnUrlTemplate;
150 private Vector<BarcodeFormat> decodeFormats;
151 private String characterSet;
152 private String versionName;
153 private HistoryManager historyManager;
155 private final OnCompletionListener beepListener = new BeepListener();
157 private final DialogInterface.OnClickListener aboutListener =
158 new DialogInterface.OnClickListener() {
159 public void onClick(DialogInterface dialogInterface, int i) {
160 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
161 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
162 startActivity(intent);
166 ViewfinderView getViewfinderView() {
167 return viewfinderView;
170 public Handler getHandler() {
175 public void onCreate(Bundle icicle) {
176 super.onCreate(icicle);
178 Window window = getWindow();
179 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
180 setContentView(R.layout.capture);
182 CameraManager.init(getApplication());
183 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
184 resultView = findViewById(R.id.result_view);
185 statusView = findViewById(R.id.status_view);
189 historyManager = new HistoryManager(this);
190 historyManager.trimHistory();
192 showHelpOnFirstLaunch();
196 protected void onResume() {
199 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
200 SurfaceHolder surfaceHolder = surfaceView.getHolder();
202 // The activity was paused but not stopped, so the surface still exists. Therefore
203 // surfaceCreated() won't be called, so init the camera here.
204 initCamera(surfaceHolder);
206 // Install the callback and wait for surfaceCreated() to init the camera.
207 surfaceHolder.addCallback(this);
208 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
211 Intent intent = getIntent();
212 String action = intent == null ? null : intent.getAction();
213 String dataString = intent == null ? null : intent.getDataString();
214 if (intent != null && action != null) {
215 if (action.equals(Intents.Scan.ACTION)) {
216 // Scan the formats the intent requested, and return the result to the calling activity.
217 source = Source.NATIVE_APP_INTENT;
218 decodeFormats = parseDecodeFormats(intent);
220 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
221 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
222 // Scan only products and send the result to mobile Product Search.
223 source = Source.PRODUCT_SEARCH_LINK;
224 sourceUrl = dataString;
225 decodeFormats = PRODUCT_FORMATS;
227 } else if (dataString != null && dataString.startsWith(ZXING_URL)) {
228 // Scan formats requested in query string (all formats if none specified).
229 // If a return URL is specified, send the results there. Otherwise, handle the results ourselves.
230 source = Source.ZXING_LINK;
231 sourceUrl = dataString;
232 Uri inputUri = Uri.parse(sourceUrl);
233 returnUrlTemplate = inputUri.getQueryParameter(RETURN_URL_PARAM);
234 decodeFormats = parseDecodeFormats(inputUri);
237 // Scan all formats and handle the results ourselves (launched from Home).
238 source = Source.NONE;
239 decodeFormats = null;
242 characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
244 source = Source.NONE;
245 decodeFormats = null;
247 if (lastResult == null) {
252 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
253 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
255 // See if sound settings overrides this
256 AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
257 if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
261 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
262 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
266 private static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
267 List<String> scanFormats = null;
268 String scanFormatsString = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
269 if (scanFormatsString != null) {
270 scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));
272 return parseDecodeFormats(scanFormats, intent.getStringExtra(Intents.Scan.MODE));
275 private static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
276 List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
277 if (formats != null && formats.size() == 1 && formats.get(0) != null){
278 formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
280 return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
283 private static Vector<BarcodeFormat> parseDecodeFormats(List<String> scanFormats,
285 if (scanFormats != null) {
286 Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
288 for (String format : scanFormats) {
289 formats.add(BarcodeFormat.valueOf(format));
292 } catch (IllegalArgumentException iae) {
296 if (decodeMode != null) {
297 if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
298 return PRODUCT_FORMATS;
300 if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
301 return QR_CODE_FORMATS;
303 if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
304 return ONE_D_FORMATS;
311 protected void onPause() {
313 if (handler != null) {
314 handler.quitSynchronously();
317 CameraManager.get().closeDriver();
321 public boolean onKeyDown(int keyCode, KeyEvent event) {
322 if (keyCode == KeyEvent.KEYCODE_BACK) {
323 if (source == Source.NATIVE_APP_INTENT) {
324 setResult(RESULT_CANCELED);
327 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
329 if (handler != null) {
330 handler.sendEmptyMessage(R.id.restart_preview);
334 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
335 // Handle these events so they don't launch the Camera app
338 return super.onKeyDown(keyCode, event);
342 public boolean onCreateOptionsMenu(Menu menu) {
343 super.onCreateOptionsMenu(menu);
344 menu.add(0, SHARE_ID, 0, R.string.menu_share)
345 .setIcon(android.R.drawable.ic_menu_share);
346 menu.add(0, HISTORY_ID, 0, R.string.menu_history)
347 .setIcon(android.R.drawable.ic_menu_recent_history);
348 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
349 .setIcon(android.R.drawable.ic_menu_preferences);
350 menu.add(0, HELP_ID, 0, R.string.menu_help)
351 .setIcon(android.R.drawable.ic_menu_help);
352 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
353 .setIcon(android.R.drawable.ic_menu_info_details);
357 // Don't display the share menu item if the result overlay is showing.
359 public boolean onPrepareOptionsMenu(Menu menu) {
360 super.onPrepareOptionsMenu(menu);
361 menu.findItem(SHARE_ID).setVisible(lastResult == null);
366 public boolean onOptionsItemSelected(MenuItem item) {
367 switch (item.getItemId()) {
369 Intent intent = new Intent(Intent.ACTION_VIEW);
370 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
371 intent.setClassName(this, ShareActivity.class.getName());
372 startActivity(intent);
376 AlertDialog historyAlert = historyManager.buildAlert();
381 Intent intent = new Intent(Intent.ACTION_VIEW);
382 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
383 intent.setClassName(this, PreferencesActivity.class.getName());
384 startActivity(intent);
388 Intent intent = new Intent(Intent.ACTION_VIEW);
389 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
390 intent.setClassName(this, HelpActivity.class.getName());
391 startActivity(intent);
395 AlertDialog.Builder builder = new AlertDialog.Builder(this);
396 builder.setTitle(getString(R.string.title_about) + versionName);
397 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
398 builder.setIcon(R.drawable.launcher_icon);
399 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
400 builder.setNegativeButton(R.string.button_cancel, null);
404 return super.onOptionsItemSelected(item);
408 public void onConfigurationChanged(Configuration config) {
409 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
410 super.onConfigurationChanged(config);
413 public void surfaceCreated(SurfaceHolder holder) {
420 public void surfaceDestroyed(SurfaceHolder holder) {
424 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
429 * A valid barcode has been found, so give an indication of success and show the results.
431 * @param rawResult The contents of the barcode.
432 * @param barcode A greyscale bitmap of the camera data which was decoded.
434 public void handleDecode(Result rawResult, Bitmap barcode) {
435 lastResult = rawResult;
436 historyManager.addHistoryItem(rawResult);
437 if (barcode == null) {
438 // This is from history -- no saved barcode
439 handleDecodeInternally(rawResult, null);
441 playBeepSoundAndVibrate();
442 drawResultPoints(barcode, rawResult);
444 case NATIVE_APP_INTENT:
445 case PRODUCT_SEARCH_LINK:
446 handleDecodeExternally(rawResult, barcode);
449 if(returnUrlTemplate == null){
450 handleDecodeInternally(rawResult, barcode);
452 handleDecodeExternally(rawResult, barcode);
456 handleDecodeInternally(rawResult, barcode);
463 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
465 * @param barcode A bitmap of the captured image.
466 * @param rawResult The decoded results which contains the points to draw.
468 private void drawResultPoints(Bitmap barcode, Result rawResult) {
469 ResultPoint[] points = rawResult.getResultPoints();
470 if (points != null && points.length > 0) {
471 Canvas canvas = new Canvas(barcode);
472 Paint paint = new Paint();
473 paint.setColor(getResources().getColor(R.color.result_image_border));
474 paint.setStrokeWidth(3.0f);
475 paint.setStyle(Paint.Style.STROKE);
476 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
477 canvas.drawRect(border, paint);
479 paint.setColor(getResources().getColor(R.color.result_points));
480 if (points.length == 2) {
481 paint.setStrokeWidth(4.0f);
482 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
483 points[1].getY(), paint);
485 paint.setStrokeWidth(10.0f);
486 for (ResultPoint point : points) {
487 canvas.drawPoint(point.getX(), point.getY(), paint);
493 // Put up our own UI for how to handle the decoded contents.
494 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
495 statusView.setVisibility(View.GONE);
496 viewfinderView.setVisibility(View.GONE);
497 resultView.setVisibility(View.VISIBLE);
499 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
500 if (barcode == null) {
501 barcodeImageView.setImageResource(R.drawable.launcher_icon_large);
503 barcodeImageView.setImageBitmap(barcode);
505 barcodeImageView.setVisibility(View.VISIBLE);
507 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
508 formatTextView.setVisibility(View.VISIBLE);
509 formatTextView.setText(rawResult.getBarcodeFormat().toString());
511 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
512 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
513 typeTextView.setVisibility(View.VISIBLE);
514 typeTextView.setText(resultHandler.getType().toString());
516 DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
517 String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
518 TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
519 timeTextView.setVisibility(View.VISIBLE);
520 timeTextView.setText(formattedTime);
522 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
523 CharSequence displayContents = resultHandler.getDisplayContents();
524 contentsTextView.setText(displayContents);
525 // Crudely scale betweeen 22 and 42 -- bigger font for shorter text
526 int scaledSize = Math.max(22, 42 - displayContents.length() / 4);
527 contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
529 int buttonCount = resultHandler.getButtonCount();
530 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
531 buttonView.requestFocus();
532 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
533 TextView button = (TextView) buttonView.getChildAt(x);
534 if (x < buttonCount) {
535 button.setVisibility(View.VISIBLE);
536 button.setText(resultHandler.getButtonText(x));
537 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
539 button.setVisibility(View.GONE);
543 if (copyToClipboard) {
544 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
545 clipboard.setText(displayContents);
549 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
550 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
551 viewfinderView.drawResultBitmap(barcode);
553 // Since this message will only be shown for a second, just tell the user what kind of
554 // barcode was found (e.g. contact info) rather than the full contents, which they won't
555 // have time to read.
556 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
557 Toast.makeText(this, resultHandler.getDisplayTitle(), Toast.LENGTH_SHORT).show();
559 if (copyToClipboard) {
560 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
561 clipboard.setText(resultHandler.getDisplayContents());
564 if (source == Source.NATIVE_APP_INTENT) {
565 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
566 // the deprecated intent is retired.
567 Intent intent = new Intent(getIntent().getAction());
568 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
569 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
570 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
571 Message message = Message.obtain(handler, R.id.return_scan_result);
572 message.obj = intent;
573 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
574 } else if (source == Source.PRODUCT_SEARCH_LINK) {
575 // Reformulate the URL which triggered us into a query, so that the request goes to the same
576 // TLD as the scan URL.
577 Message message = Message.obtain(handler, R.id.launch_product_query);
578 int end = sourceUrl.lastIndexOf("/scan");
579 message.obj = sourceUrl.substring(0, end) + "?q=" +
580 resultHandler.getDisplayContents().toString() + "&source=zxing";
581 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
582 } else if (source == Source.ZXING_LINK) {
583 // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate
584 // with the scanned code. This allows both queries and REST-style URLs to work.
585 Message message = Message.obtain(handler, R.id.launch_product_query);
586 message.obj = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER, resultHandler.getDisplayContents().toString());
587 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
592 * We want the help screen to be shown automatically the first time a new version of the app is
593 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
594 * it to a value stored as a preference.
596 private boolean showHelpOnFirstLaunch() {
598 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
599 int currentVersion = info.versionCode;
600 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
601 // version name here for display in the about box later.
602 this.versionName = info.versionName;
603 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
604 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
605 if (currentVersion > lastVersion) {
606 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
607 Intent intent = new Intent(this, HelpActivity.class);
608 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
609 // Show the default page on a clean install, and the what's new page on an upgrade.
610 String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
611 intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
612 startActivity(intent);
615 } catch (PackageManager.NameNotFoundException e) {
622 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
625 private void initBeepSound() {
626 if (playBeep && mediaPlayer == null) {
627 // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
628 // so we now play on the music stream.
629 setVolumeControlStream(AudioManager.STREAM_MUSIC);
630 mediaPlayer = new MediaPlayer();
631 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
632 mediaPlayer.setOnCompletionListener(beepListener);
634 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
636 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
639 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
640 mediaPlayer.prepare();
641 } catch (IOException e) {
647 private void playBeepSoundAndVibrate() {
648 if (playBeep && mediaPlayer != null) {
652 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
653 vibrator.vibrate(VIBRATE_DURATION);
657 private void initCamera(SurfaceHolder surfaceHolder) {
659 CameraManager.get().openDriver(surfaceHolder);
660 } catch (IOException ioe) {
662 displayFrameworkBugMessageAndExit();
664 } catch (RuntimeException e) {
665 // Barcode Scanner has seen crashes in the wild of this variety:
666 // java.?lang.?RuntimeException: Fail to connect to camera service
667 Log.w(TAG, "Unexpected error initializating camera", e);
668 displayFrameworkBugMessageAndExit();
671 if (handler == null) {
672 boolean beginScanning = lastResult == null;
673 handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
677 private void displayFrameworkBugMessageAndExit() {
678 AlertDialog.Builder builder = new AlertDialog.Builder(this);
679 builder.setTitle(getString(R.string.app_name));
680 builder.setMessage(getString(R.string.msg_camera_framework_bug));
681 builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
682 public void onClick(DialogInterface dialogInterface, int i) {
689 private void resetStatusView() {
690 resultView.setVisibility(View.GONE);
691 statusView.setVisibility(View.VISIBLE);
692 viewfinderView.setVisibility(View.VISIBLE);
696 public void drawViewfinder() {
697 viewfinderView.drawViewfinder();
701 * When the beep has finished playing, rewind to queue up another one.
703 private static class BeepListener implements OnCompletionListener {
704 public void onCompletion(MediaPlayer mediaPlayer) {
705 mediaPlayer.seekTo(0);