2d9b014e26c7297d5c2304f4b702ba9ab60a1da4
[zxing.git] / android / src / com / google / zxing / client / android / CaptureActivity.java
1 /*
2  * Copyright (C) 2008 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.client.android;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
22 import com.google.zxing.client.android.history.HistoryManager;
23 import com.google.zxing.client.android.result.ResultButtonListener;
24 import com.google.zxing.client.android.result.ResultHandler;
25 import com.google.zxing.client.android.result.ResultHandlerFactory;
26 import com.google.zxing.client.android.share.ShareActivity;
27
28 import android.app.Activity;
29 import android.app.AlertDialog;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.SharedPreferences;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager;
35 import android.content.res.AssetFileDescriptor;
36 import android.content.res.Configuration;
37 import android.graphics.Bitmap;
38 import android.graphics.Canvas;
39 import android.graphics.Paint;
40 import android.graphics.Rect;
41 import android.graphics.drawable.BitmapDrawable;
42 import android.media.AudioManager;
43 import android.media.MediaPlayer;
44 import android.media.MediaPlayer.OnCompletionListener;
45 import android.net.Uri;
46 import android.os.Bundle;
47 import android.os.Handler;
48 import android.os.Message;
49 import android.os.Vibrator;
50 import android.preference.PreferenceManager;
51 import android.text.ClipboardManager;
52 import android.text.SpannableStringBuilder;
53 import android.text.style.UnderlineSpan;
54 import android.util.Log;
55 import android.view.Gravity;
56 import android.view.KeyEvent;
57 import android.view.Menu;
58 import android.view.MenuItem;
59 import android.view.SurfaceHolder;
60 import android.view.SurfaceView;
61 import android.view.View;
62 import android.view.ViewGroup;
63 import android.view.Window;
64 import android.view.WindowManager;
65 import android.widget.ImageView;
66 import android.widget.TextView;
67
68 import java.io.IOException;
69 import java.util.Vector;
70 import java.util.regex.Pattern;
71
72 /**
73  * The barcode reader activity itself. This is loosely based on the CameraPreview
74  * example included in the Android SDK.
75  *
76  * @author dswitkin@google.com (Daniel Switkin)
77  */
78 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
79
80   private static final String TAG = "CaptureActivity";
81   private static final Pattern COMMA_PATTERN = Pattern.compile(",");
82
83   private static final int SHARE_ID = Menu.FIRST;
84   private static final int HISTORY_ID = Menu.FIRST + 1;
85   private static final int SETTINGS_ID = Menu.FIRST + 2;
86   private static final int HELP_ID = Menu.FIRST + 3;
87   private static final int ABOUT_ID = Menu.FIRST + 4;
88
89   private static final int MAX_RESULT_IMAGE_SIZE = 150;
90   private static final long INTENT_RESULT_DURATION = 1500L;
91   private static final float BEEP_VOLUME = 0.10f;
92   private static final long VIBRATE_DURATION = 200L;
93
94   private static final String PACKAGE_NAME = "com.google.zxing.client.android";
95   private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
96   private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
97   private static final String ZXING_URL = "http://zxing.appspot.com/scan";
98
99   static final Vector<BarcodeFormat> PRODUCT_FORMATS;
100   static final Vector<BarcodeFormat> ONE_D_FORMATS;
101   static final Vector<BarcodeFormat> QR_CODE_FORMATS;
102   static final Vector<BarcodeFormat> ALL_FORMATS;
103
104   static {
105     PRODUCT_FORMATS = new Vector<BarcodeFormat>(5);
106     PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
107     PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
108     PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
109     PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
110     PRODUCT_FORMATS.add(BarcodeFormat.RSS14);
111     ONE_D_FORMATS = new Vector<BarcodeFormat>(PRODUCT_FORMATS.size() + 3);
112     ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
113     ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
114     ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
115     ONE_D_FORMATS.add(BarcodeFormat.ITF);
116     QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
117     QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
118     ALL_FORMATS = new Vector<BarcodeFormat>(ONE_D_FORMATS.size() + QR_CODE_FORMATS.size());
119     ALL_FORMATS.addAll(ONE_D_FORMATS);
120     ALL_FORMATS.addAll(QR_CODE_FORMATS);
121   }
122
123   private enum Source {
124     NATIVE_APP_INTENT,
125     PRODUCT_SEARCH_LINK,
126     ZXING_LINK,
127     NONE
128   }
129
130   private CaptureActivityHandler handler;
131
132   private ViewfinderView viewfinderView;
133   private View statusView;
134   private View resultView;
135   private MediaPlayer mediaPlayer;
136   private Result lastResult;
137   private boolean hasSurface;
138   private boolean playBeep;
139   private boolean vibrate;
140   private boolean copyToClipboard;
141   private Source source;
142   private String sourceUrl;
143   private Vector<BarcodeFormat> decodeFormats;
144   private String characterSet;
145   private String versionName;
146   private HistoryManager historyManager;
147
148   private final OnCompletionListener beepListener = new BeepListener();
149
150   private final DialogInterface.OnClickListener aboutListener =
151       new DialogInterface.OnClickListener() {
152     public void onClick(DialogInterface dialogInterface, int i) {
153       Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
154       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
155       startActivity(intent);
156     }
157   };
158
159   ViewfinderView getViewfinderView() {
160     return viewfinderView;
161   }
162
163   public Handler getHandler() {
164     return handler;
165   }
166
167   @Override
168   public void onCreate(Bundle icicle) {
169     super.onCreate(icicle);
170
171     Window window = getWindow();
172     window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
173     setContentView(R.layout.capture);
174
175     CameraManager.init(getApplication());
176     viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
177     resultView = findViewById(R.id.result_view);
178     statusView = findViewById(R.id.status_view);
179     handler = null;
180     lastResult = null;
181     hasSurface = false;
182     historyManager = new HistoryManager(this);
183     historyManager.trimHistory();
184
185     showHelpOnFirstLaunch();
186   }
187
188   @Override
189   protected void onResume() {
190     super.onResume();
191
192     SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
193     SurfaceHolder surfaceHolder = surfaceView.getHolder();
194     if (hasSurface) {
195       // The activity was paused but not stopped, so the surface still exists. Therefore
196       // surfaceCreated() won't be called, so init the camera here.
197       initCamera(surfaceHolder);
198     } else {
199       // Install the callback and wait for surfaceCreated() to init the camera.
200       surfaceHolder.addCallback(this);
201       surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
202     }
203
204     Intent intent = getIntent();
205     String action = intent == null ? null : intent.getAction();
206     String dataString = intent == null ? null : intent.getDataString();
207     if (intent != null && action != null) {
208       if (action.equals(Intents.Scan.ACTION)) {
209         // Scan the formats the intent requested, and return the result to the calling activity.
210         source = Source.NATIVE_APP_INTENT;
211         decodeFormats = parseDecodeFormats(intent);
212         resetStatusView();
213       } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
214           dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
215         // Scan only products and send the result to mobile Product Search.
216         source = Source.PRODUCT_SEARCH_LINK;
217         sourceUrl = dataString;
218         decodeFormats = PRODUCT_FORMATS;
219         resetStatusView();
220       } else if (dataString != null && dataString.equals(ZXING_URL)) {
221         // Scan all formats and handle the results ourselves.
222         // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
223         source = Source.ZXING_LINK;
224         sourceUrl = dataString;
225         decodeFormats = null;
226         resetStatusView();
227       } else {
228         // Scan all formats and handle the results ourselves (launched from Home).
229         source = Source.NONE;
230         decodeFormats = null;
231         resetStatusView();
232       }
233       characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
234     } else {
235       source = Source.NONE;
236       decodeFormats = null;
237       characterSet = null;
238       if (lastResult == null) {
239         resetStatusView();
240       }
241     }
242
243     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
244     playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
245     vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
246     copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
247     initBeepSound();
248   }
249
250   private static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
251     String scanFormats = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
252     if (scanFormats != null) {
253       Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
254       try {
255         for (String format : COMMA_PATTERN.split(scanFormats)) {
256           formats.add(BarcodeFormat.valueOf(format));
257         }
258         return formats;
259       } catch (IllegalArgumentException iae) {
260         // ignore it then
261       }
262     }
263     String decodeMode = intent.getStringExtra(Intents.Scan.MODE);
264     if (decodeMode != null) {
265       if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
266         return PRODUCT_FORMATS;
267       }
268       if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
269         return QR_CODE_FORMATS;
270       }
271       if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
272         return ONE_D_FORMATS;
273       }
274     }
275     return null;
276   }
277
278   @Override
279   protected void onPause() {
280     super.onPause();
281     if (handler != null) {
282       handler.quitSynchronously();
283       handler = null;
284     }
285     CameraManager.get().closeDriver();
286   }
287
288   @Override
289   public boolean onKeyDown(int keyCode, KeyEvent event) {
290     if (keyCode == KeyEvent.KEYCODE_BACK) {
291       if (source == Source.NATIVE_APP_INTENT) {
292         setResult(RESULT_CANCELED);
293         finish();
294         return true;
295       } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
296         resetStatusView();
297         if (handler != null) {
298           handler.sendEmptyMessage(R.id.restart_preview);
299         }
300         return true;
301       }
302     } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
303       // Handle these events so they don't launch the Camera app
304       return true;
305     }
306     return super.onKeyDown(keyCode, event);
307   }
308
309   @Override
310   public boolean onCreateOptionsMenu(Menu menu) {
311     super.onCreateOptionsMenu(menu);
312     menu.add(0, SHARE_ID, 0, R.string.menu_share)
313         .setIcon(android.R.drawable.ic_menu_share);
314     menu.add(0, HISTORY_ID, 0, R.string.menu_history)
315         .setIcon(android.R.drawable.ic_menu_recent_history);
316     menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
317         .setIcon(android.R.drawable.ic_menu_preferences);
318     menu.add(0, HELP_ID, 0, R.string.menu_help)
319         .setIcon(android.R.drawable.ic_menu_help);
320     menu.add(0, ABOUT_ID, 0, R.string.menu_about)
321         .setIcon(android.R.drawable.ic_menu_info_details);
322     return true;
323   }
324
325   // Don't display the share menu item if the result overlay is showing.
326   @Override
327   public boolean onPrepareOptionsMenu(Menu menu) {
328     super.onPrepareOptionsMenu(menu);
329     menu.findItem(SHARE_ID).setVisible(lastResult == null);
330     return true;
331   }
332
333   @Override
334   public boolean onOptionsItemSelected(MenuItem item) {
335     switch (item.getItemId()) {
336       case SHARE_ID: {
337         Intent intent = new Intent(Intent.ACTION_VIEW);
338         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
339         intent.setClassName(this, ShareActivity.class.getName());
340         startActivity(intent);
341         break;
342       }
343       case HISTORY_ID: {
344         AlertDialog historyAlert = historyManager.buildAlert();
345         historyAlert.show();
346         break;
347       }
348       case SETTINGS_ID: {
349         Intent intent = new Intent(Intent.ACTION_VIEW);
350         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
351         intent.setClassName(this, PreferencesActivity.class.getName());
352         startActivity(intent);
353         break;
354       }
355       case HELP_ID: {
356         Intent intent = new Intent(Intent.ACTION_VIEW);
357         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
358         intent.setClassName(this, HelpActivity.class.getName());
359         startActivity(intent);
360         break;
361       }
362       case ABOUT_ID:
363         AlertDialog.Builder builder = new AlertDialog.Builder(this);
364         builder.setTitle(getString(R.string.title_about) + versionName);
365         builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
366         builder.setIcon(R.drawable.zxing_icon);
367         builder.setPositiveButton(R.string.button_open_browser, aboutListener);
368         builder.setNegativeButton(R.string.button_cancel, null);
369         builder.show();
370         break;
371     }
372     return super.onOptionsItemSelected(item);
373   }
374
375   @Override
376   public void onConfigurationChanged(Configuration config) {
377     // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
378     super.onConfigurationChanged(config);
379   }
380
381   public void surfaceCreated(SurfaceHolder holder) {
382     if (!hasSurface) {
383       hasSurface = true;
384       initCamera(holder);
385     }
386   }
387
388   public void surfaceDestroyed(SurfaceHolder holder) {
389     hasSurface = false;
390   }
391
392   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
393
394   }
395
396   /**
397    * A valid barcode has been found, so give an indication of success and show the results.
398    *
399    * @param rawResult The contents of the barcode.
400    * @param barcode   A greyscale bitmap of the camera data which was decoded.
401    */
402   public void handleDecode(Result rawResult, Bitmap barcode) {
403     lastResult = rawResult;
404     historyManager.addHistoryItem(rawResult);
405     if (barcode == null) {
406       // This is from history -- no saved barcode
407       handleDecodeInternally(rawResult, null);
408     } else {
409       playBeepSoundAndVibrate();
410       drawResultPoints(barcode, rawResult);
411       switch (source) {
412         case NATIVE_APP_INTENT:
413         case PRODUCT_SEARCH_LINK:
414           handleDecodeExternally(rawResult, barcode);
415           break;
416         case ZXING_LINK:
417         case NONE:
418           handleDecodeInternally(rawResult, barcode);
419           break;
420       }
421     }
422   }
423
424   /**
425    * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
426    *
427    * @param barcode   A bitmap of the captured image.
428    * @param rawResult The decoded results which contains the points to draw.
429    */
430   private void drawResultPoints(Bitmap barcode, Result rawResult) {
431     ResultPoint[] points = rawResult.getResultPoints();
432     if (points != null && points.length > 0) {
433       Canvas canvas = new Canvas(barcode);
434       Paint paint = new Paint();
435       paint.setColor(getResources().getColor(R.color.result_image_border));
436       paint.setStrokeWidth(3.0f);
437       paint.setStyle(Paint.Style.STROKE);
438       Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
439       canvas.drawRect(border, paint);
440
441       paint.setColor(getResources().getColor(R.color.result_points));
442       if (points.length == 2) {
443         paint.setStrokeWidth(4.0f);
444         canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
445             points[1].getY(), paint);
446       } else {
447         paint.setStrokeWidth(10.0f);
448         for (ResultPoint point : points) {
449           canvas.drawPoint(point.getX(), point.getY(), paint);
450         }
451       }
452     }
453   }
454
455   // Put up our own UI for how to handle the decoded contents.
456   private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
457     statusView.setVisibility(View.GONE);
458     viewfinderView.setVisibility(View.GONE);
459     resultView.setVisibility(View.VISIBLE);
460
461     if (barcode == null) {
462       barcode = ((BitmapDrawable) getResources().getDrawable(R.drawable.unknown_barcode)).getBitmap();
463     }
464     ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
465     barcodeImageView.setVisibility(View.VISIBLE);
466     barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
467     barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
468     barcodeImageView.setImageBitmap(barcode);
469
470     TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
471     formatTextView.setVisibility(View.VISIBLE);
472     formatTextView.setText(getString(R.string.msg_default_format) + ": " +
473         rawResult.getBarcodeFormat().toString());
474
475     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
476     TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
477     typeTextView.setText(getString(R.string.msg_default_type) + ": " +
478         resultHandler.getType().toString());
479
480     TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
481     CharSequence title = getString(resultHandler.getDisplayTitle());
482     SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
483     styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
484     CharSequence displayContents = resultHandler.getDisplayContents();
485     styled.append(displayContents);
486     contentsTextView.setText(styled);
487
488     int buttonCount = resultHandler.getButtonCount();
489     ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
490     buttonView.requestFocus();
491     for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
492       TextView button = (TextView) buttonView.getChildAt(x);
493       if (x < buttonCount) {
494         button.setVisibility(View.VISIBLE);
495         button.setText(resultHandler.getButtonText(x));
496         button.setOnClickListener(new ResultButtonListener(resultHandler, x));
497       } else {
498         button.setVisibility(View.GONE);
499       }
500     }
501
502     if (copyToClipboard) {
503       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
504       clipboard.setText(displayContents);
505     }
506   }
507
508   // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
509   private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
510     viewfinderView.drawResultBitmap(barcode);
511
512     // Since this message will only be shown for a second, just tell the user what kind of
513     // barcode was found (e.g. contact info) rather than the full contents, which they won't
514     // have time to read.
515     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
516     TextView textView = (TextView) findViewById(R.id.status_text_view);
517     textView.setGravity(Gravity.CENTER);
518     textView.setTextSize(18.0f);
519     textView.setText(getString(resultHandler.getDisplayTitle()));
520
521     statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
522
523     if (copyToClipboard) {
524       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
525       clipboard.setText(resultHandler.getDisplayContents());
526     }
527
528     if (source == Source.NATIVE_APP_INTENT) {
529       // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
530       // the deprecated intent is retired.
531       Intent intent = new Intent(getIntent().getAction());
532       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
533       intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
534       intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
535       Message message = Message.obtain(handler, R.id.return_scan_result);
536       message.obj = intent;
537       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
538     } else if (source == Source.PRODUCT_SEARCH_LINK) {
539       // Reformulate the URL which triggered us into a query, so that the request goes to the same
540       // TLD as the scan URL.
541       Message message = Message.obtain(handler, R.id.launch_product_query);
542       int end = sourceUrl.lastIndexOf("/scan");
543       message.obj = sourceUrl.substring(0, end) + "?q=" +
544           resultHandler.getDisplayContents().toString() + "&source=zxing";
545       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
546     }
547   }
548
549   /**
550    * We want the help screen to be shown automatically the first time a new version of the app is
551    * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
552    * it to a value stored as a preference.
553    */
554   private boolean showHelpOnFirstLaunch() {
555     try {
556       PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
557       int currentVersion = info.versionCode;
558       // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
559       // version name here for display in the about box later.
560       this.versionName = info.versionName;
561       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
562       int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
563       if (currentVersion > lastVersion) {
564         prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
565         Intent intent = new Intent(this, HelpActivity.class);
566         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
567         // Show the default page on a clean install, and the what's new page on an upgrade.
568         String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
569         intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
570         startActivity(intent);
571         return true;
572       }
573     } catch (PackageManager.NameNotFoundException e) {
574       Log.w(TAG, e);
575     }
576     return false;
577   }
578
579   /**
580    * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
581    * latency possible.
582    */
583   private void initBeepSound() {
584     if (playBeep && mediaPlayer == null) {
585       // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
586       // so we now play on the music stream.
587       setVolumeControlStream(AudioManager.STREAM_MUSIC);
588       mediaPlayer = new MediaPlayer();
589       mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
590       mediaPlayer.setOnCompletionListener(beepListener);
591
592       AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
593       try {
594         mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
595             file.getLength());
596         file.close();
597         mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
598         mediaPlayer.prepare();
599       } catch (IOException e) {
600         mediaPlayer = null;
601       }
602     }
603   }
604
605   private void playBeepSoundAndVibrate() {
606     if (playBeep && mediaPlayer != null) {
607       mediaPlayer.start();
608     }
609     if (vibrate) {
610       Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
611       vibrator.vibrate(VIBRATE_DURATION);
612     }
613   }
614
615   private void initCamera(SurfaceHolder surfaceHolder) {
616     try {
617       CameraManager.get().openDriver(surfaceHolder);
618     } catch (IOException ioe) {
619       Log.w(TAG, ioe);
620       displayFrameworkBugMessageAndExit();
621       return;
622     } catch (RuntimeException e) {
623       // Barcode Scanner has seen crashes in the wild of this variety:
624       // java.?lang.?RuntimeException: Fail to connect to camera service
625       Log.e(TAG, e.toString());
626       displayFrameworkBugMessageAndExit();
627       return;
628     }
629     if (handler == null) {
630       boolean beginScanning = lastResult == null;
631       handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
632     }
633   }
634
635   private void displayFrameworkBugMessageAndExit() {
636     AlertDialog.Builder builder = new AlertDialog.Builder(this);
637     builder.setTitle(getString(R.string.app_name));
638     builder.setMessage(getString(R.string.msg_camera_framework_bug));
639     builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
640       public void onClick(DialogInterface dialogInterface, int i) {
641         finish();
642       }
643     });
644     builder.show();
645   }
646
647   private void resetStatusView() {
648     resultView.setVisibility(View.GONE);
649     statusView.setVisibility(View.VISIBLE);
650     statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
651     viewfinderView.setVisibility(View.VISIBLE);
652
653     TextView textView = (TextView) findViewById(R.id.status_text_view);
654     textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
655     textView.setTextSize(14.0f);
656     textView.setText(R.string.msg_default_status);
657     lastResult = null;
658   }
659
660   public void drawViewfinder() {
661     viewfinderView.drawViewfinder();
662   }
663
664   /**
665    * When the beep has finished playing, rewind to queue up another one.
666    */
667   private static class BeepListener implements OnCompletionListener {
668     public void onCompletion(MediaPlayer mediaPlayer) {
669       mediaPlayer.seekTo(0);
670     }
671   }
672 }