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