Added send barcode feature
[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.media.AudioManager;
42 import android.media.MediaPlayer;
43 import android.media.MediaPlayer.OnCompletionListener;
44 import android.net.Uri;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.os.Message;
48 import android.os.Vibrator;
49 import android.preference.PreferenceManager;
50 import android.text.ClipboardManager;
51 import android.text.SpannableStringBuilder;
52 import android.text.style.UnderlineSpan;
53 import android.util.Log;
54 import android.view.Gravity;
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;
66
67 import java.io.IOException;
68 import java.text.DateFormat;
69 import java.util.Date;
70 import java.util.Vector;
71 import java.util.regex.Pattern;
72
73 /**
74  * The barcode reader activity itself. This is loosely based on the CameraPreview
75  * example included in the Android SDK.
76  *
77  * @author dswitkin@google.com (Daniel Switkin)
78  */
79 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
80
81   private static final String TAG = "CaptureActivity";
82   private static final Pattern COMMA_PATTERN = Pattern.compile(",");
83
84   private static final int SHARE_ID = Menu.FIRST;
85   private static final int HISTORY_ID = Menu.FIRST + 1;
86   private static final int SETTINGS_ID = Menu.FIRST + 2;
87   private static final int HELP_ID = Menu.FIRST + 3;
88   private static final int ABOUT_ID = Menu.FIRST + 4;
89
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     ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
462     if (barcode == null) {
463       barcodeImageView.setImageResource(R.drawable.zxing_icon);
464     } else {
465       barcodeImageView.setImageBitmap(barcode);
466     }
467     barcodeImageView.setVisibility(View.VISIBLE);
468
469     TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
470     formatTextView.setVisibility(View.VISIBLE);
471     formatTextView.setText(getString(R.string.msg_default_format) + ": " +
472         rawResult.getBarcodeFormat().toString());
473
474     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
475     TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
476     typeTextView.setVisibility(View.VISIBLE);
477     typeTextView.setText(getString(R.string.msg_default_type) + ": " +
478         resultHandler.getType().toString());
479
480     DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
481     String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
482     TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
483     timeTextView.setVisibility(View.VISIBLE);
484     timeTextView.setText(getString(R.string.msg_default_time) + ": " + formattedTime);
485
486     TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
487     CharSequence title = getString(resultHandler.getDisplayTitle());
488     SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
489     styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
490     CharSequence displayContents = resultHandler.getDisplayContents();
491     styled.append(displayContents);
492     contentsTextView.setText(styled);
493
494     int buttonCount = resultHandler.getButtonCount();
495     ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
496     buttonView.requestFocus();
497     for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
498       TextView button = (TextView) buttonView.getChildAt(x);
499       if (x < buttonCount) {
500         button.setVisibility(View.VISIBLE);
501         button.setText(resultHandler.getButtonText(x));
502         button.setOnClickListener(new ResultButtonListener(resultHandler, x));
503       } else {
504         button.setVisibility(View.GONE);
505       }
506     }
507
508     if (copyToClipboard) {
509       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
510       clipboard.setText(displayContents);
511     }
512   }
513
514   // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
515   private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
516     viewfinderView.drawResultBitmap(barcode);
517
518     // Since this message will only be shown for a second, just tell the user what kind of
519     // barcode was found (e.g. contact info) rather than the full contents, which they won't
520     // have time to read.
521     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
522     TextView textView = (TextView) findViewById(R.id.status_text_view);
523     textView.setGravity(Gravity.CENTER);
524     textView.setTextSize(18.0f);
525     textView.setText(getString(resultHandler.getDisplayTitle()));
526
527     statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
528
529     if (copyToClipboard) {
530       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
531       clipboard.setText(resultHandler.getDisplayContents());
532     }
533
534     if (source == Source.NATIVE_APP_INTENT) {
535       // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
536       // the deprecated intent is retired.
537       Intent intent = new Intent(getIntent().getAction());
538       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
539       intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
540       intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
541       Message message = Message.obtain(handler, R.id.return_scan_result);
542       message.obj = intent;
543       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
544     } else if (source == Source.PRODUCT_SEARCH_LINK) {
545       // Reformulate the URL which triggered us into a query, so that the request goes to the same
546       // TLD as the scan URL.
547       Message message = Message.obtain(handler, R.id.launch_product_query);
548       int end = sourceUrl.lastIndexOf("/scan");
549       message.obj = sourceUrl.substring(0, end) + "?q=" +
550           resultHandler.getDisplayContents().toString() + "&source=zxing";
551       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
552     }
553   }
554
555   /**
556    * We want the help screen to be shown automatically the first time a new version of the app is
557    * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
558    * it to a value stored as a preference.
559    */
560   private boolean showHelpOnFirstLaunch() {
561     try {
562       PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
563       int currentVersion = info.versionCode;
564       // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
565       // version name here for display in the about box later.
566       this.versionName = info.versionName;
567       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
568       int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
569       if (currentVersion > lastVersion) {
570         prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
571         Intent intent = new Intent(this, HelpActivity.class);
572         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
573         // Show the default page on a clean install, and the what's new page on an upgrade.
574         String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
575         intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
576         startActivity(intent);
577         return true;
578       }
579     } catch (PackageManager.NameNotFoundException e) {
580       Log.w(TAG, e);
581     }
582     return false;
583   }
584
585   /**
586    * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
587    * latency possible.
588    */
589   private void initBeepSound() {
590     if (playBeep && mediaPlayer == null) {
591       // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
592       // so we now play on the music stream.
593       setVolumeControlStream(AudioManager.STREAM_MUSIC);
594       mediaPlayer = new MediaPlayer();
595       mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
596       mediaPlayer.setOnCompletionListener(beepListener);
597
598       AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
599       try {
600         mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
601             file.getLength());
602         file.close();
603         mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
604         mediaPlayer.prepare();
605       } catch (IOException e) {
606         mediaPlayer = null;
607       }
608     }
609   }
610
611   private void playBeepSoundAndVibrate() {
612     if (playBeep && mediaPlayer != null) {
613       mediaPlayer.start();
614     }
615     if (vibrate) {
616       Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
617       vibrator.vibrate(VIBRATE_DURATION);
618     }
619   }
620
621   private void initCamera(SurfaceHolder surfaceHolder) {
622     try {
623       CameraManager.get().openDriver(surfaceHolder);
624     } catch (IOException ioe) {
625       Log.w(TAG, ioe);
626       displayFrameworkBugMessageAndExit();
627       return;
628     } catch (RuntimeException e) {
629       // Barcode Scanner has seen crashes in the wild of this variety:
630       // java.?lang.?RuntimeException: Fail to connect to camera service
631       Log.e(TAG, e.toString());
632       displayFrameworkBugMessageAndExit();
633       return;
634     }
635     if (handler == null) {
636       boolean beginScanning = lastResult == null;
637       handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
638     }
639   }
640
641   private void displayFrameworkBugMessageAndExit() {
642     AlertDialog.Builder builder = new AlertDialog.Builder(this);
643     builder.setTitle(getString(R.string.app_name));
644     builder.setMessage(getString(R.string.msg_camera_framework_bug));
645     builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
646       public void onClick(DialogInterface dialogInterface, int i) {
647         finish();
648       }
649     });
650     builder.show();
651   }
652
653   private void resetStatusView() {
654     resultView.setVisibility(View.GONE);
655     statusView.setVisibility(View.VISIBLE);
656     statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
657     viewfinderView.setVisibility(View.VISIBLE);
658
659     TextView textView = (TextView) findViewById(R.id.status_text_view);
660     textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
661     textView.setTextSize(14.0f);
662     textView.setText(R.string.msg_default_status);
663     lastResult = null;
664   }
665
666   public void drawViewfinder() {
667     viewfinderView.drawViewfinder();
668   }
669
670   /**
671    * When the beep has finished playing, rewind to queue up another one.
672    */
673   private static class BeepListener implements OnCompletionListener {
674     public void onCompletion(MediaPlayer mediaPlayer) {
675       mediaPlayer.seekTo(0);
676     }
677   }
678 }