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