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