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