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