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