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