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