068d5788a18af182a13f170e1ec9f1298631f5e1
[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     return parseDecodeFormats(
268         Arrays.asList(COMMA_PATTERN.split(intent.getStringExtra(Intents.Scan.SCAN_FORMATS))),
269         intent.getStringExtra(Intents.Scan.MODE));
270   }
271   
272   private static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
273     List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
274     if (formats.size() == 1){
275       formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
276     }
277     return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
278   }
279   
280   private static Vector<BarcodeFormat> parseDecodeFormats(List<String> scanFormats,
281                                                           String decodeMode) {
282     if (scanFormats != null) {
283       Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
284       try {
285         for (String format : scanFormats) {
286           formats.add(BarcodeFormat.valueOf(format));
287         }
288         return formats;
289       } catch (IllegalArgumentException iae) {
290         // ignore it then
291       }
292     }
293     if (decodeMode != null) {
294       if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
295         return PRODUCT_FORMATS;
296       }
297       if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
298         return QR_CODE_FORMATS;
299       }
300       if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
301         return ONE_D_FORMATS;
302       }
303     }
304     return null;
305   }
306
307   @Override
308   protected void onPause() {
309     super.onPause();
310     if (handler != null) {
311       handler.quitSynchronously();
312       handler = null;
313     }
314     CameraManager.get().closeDriver();
315   }
316
317   @Override
318   public boolean onKeyDown(int keyCode, KeyEvent event) {
319     if (keyCode == KeyEvent.KEYCODE_BACK) {
320       if (source == Source.NATIVE_APP_INTENT) {
321         setResult(RESULT_CANCELED);
322         finish();
323         return true;
324       } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
325         resetStatusView();
326         if (handler != null) {
327           handler.sendEmptyMessage(R.id.restart_preview);
328         }
329         return true;
330       }
331     } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
332       // Handle these events so they don't launch the Camera app
333       return true;
334     }
335     return super.onKeyDown(keyCode, event);
336   }
337
338   @Override
339   public boolean onCreateOptionsMenu(Menu menu) {
340     super.onCreateOptionsMenu(menu);
341     menu.add(0, SHARE_ID, 0, R.string.menu_share)
342         .setIcon(android.R.drawable.ic_menu_share);
343     menu.add(0, HISTORY_ID, 0, R.string.menu_history)
344         .setIcon(android.R.drawable.ic_menu_recent_history);
345     menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
346         .setIcon(android.R.drawable.ic_menu_preferences);
347     menu.add(0, HELP_ID, 0, R.string.menu_help)
348         .setIcon(android.R.drawable.ic_menu_help);
349     menu.add(0, ABOUT_ID, 0, R.string.menu_about)
350         .setIcon(android.R.drawable.ic_menu_info_details);
351     return true;
352   }
353
354   // Don't display the share menu item if the result overlay is showing.
355   @Override
356   public boolean onPrepareOptionsMenu(Menu menu) {
357     super.onPrepareOptionsMenu(menu);
358     menu.findItem(SHARE_ID).setVisible(lastResult == null);
359     return true;
360   }
361
362   @Override
363   public boolean onOptionsItemSelected(MenuItem item) {
364     switch (item.getItemId()) {
365       case SHARE_ID: {
366         Intent intent = new Intent(Intent.ACTION_VIEW);
367         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
368         intent.setClassName(this, ShareActivity.class.getName());
369         startActivity(intent);
370         break;
371       }
372       case HISTORY_ID: {
373         AlertDialog historyAlert = historyManager.buildAlert();
374         historyAlert.show();
375         break;
376       }
377       case SETTINGS_ID: {
378         Intent intent = new Intent(Intent.ACTION_VIEW);
379         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
380         intent.setClassName(this, PreferencesActivity.class.getName());
381         startActivity(intent);
382         break;
383       }
384       case HELP_ID: {
385         Intent intent = new Intent(Intent.ACTION_VIEW);
386         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
387         intent.setClassName(this, HelpActivity.class.getName());
388         startActivity(intent);
389         break;
390       }
391       case ABOUT_ID:
392         AlertDialog.Builder builder = new AlertDialog.Builder(this);
393         builder.setTitle(getString(R.string.title_about) + versionName);
394         builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
395         builder.setIcon(R.drawable.zxing_icon);
396         builder.setPositiveButton(R.string.button_open_browser, aboutListener);
397         builder.setNegativeButton(R.string.button_cancel, null);
398         builder.show();
399         break;
400     }
401     return super.onOptionsItemSelected(item);
402   }
403
404   @Override
405   public void onConfigurationChanged(Configuration config) {
406     // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
407     super.onConfigurationChanged(config);
408   }
409
410   public void surfaceCreated(SurfaceHolder holder) {
411     if (!hasSurface) {
412       hasSurface = true;
413       initCamera(holder);
414     }
415   }
416
417   public void surfaceDestroyed(SurfaceHolder holder) {
418     hasSurface = false;
419   }
420
421   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
422
423   }
424
425   /**
426    * A valid barcode has been found, so give an indication of success and show the results.
427    *
428    * @param rawResult The contents of the barcode.
429    * @param barcode   A greyscale bitmap of the camera data which was decoded.
430    */
431   public void handleDecode(Result rawResult, Bitmap barcode) {
432     lastResult = rawResult;
433     historyManager.addHistoryItem(rawResult);
434     if (barcode == null) {
435       // This is from history -- no saved barcode
436       handleDecodeInternally(rawResult, null);
437     } else {
438       playBeepSoundAndVibrate();
439       drawResultPoints(barcode, rawResult);
440       switch (source) {
441         case NATIVE_APP_INTENT:
442         case PRODUCT_SEARCH_LINK:
443           handleDecodeExternally(rawResult, barcode);
444           break;
445         case ZXING_LINK:
446           if(returnUrlTemplate == null){
447             handleDecodeInternally(rawResult, barcode);
448           } else {
449             handleDecodeExternally(rawResult, barcode);
450           }
451           break;
452         case NONE:
453           handleDecodeInternally(rawResult, barcode);
454           break;
455       }
456     }
457   }
458
459   /**
460    * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
461    *
462    * @param barcode   A bitmap of the captured image.
463    * @param rawResult The decoded results which contains the points to draw.
464    */
465   private void drawResultPoints(Bitmap barcode, Result rawResult) {
466     ResultPoint[] points = rawResult.getResultPoints();
467     if (points != null && points.length > 0) {
468       Canvas canvas = new Canvas(barcode);
469       Paint paint = new Paint();
470       paint.setColor(getResources().getColor(R.color.result_image_border));
471       paint.setStrokeWidth(3.0f);
472       paint.setStyle(Paint.Style.STROKE);
473       Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
474       canvas.drawRect(border, paint);
475
476       paint.setColor(getResources().getColor(R.color.result_points));
477       if (points.length == 2) {
478         paint.setStrokeWidth(4.0f);
479         canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
480             points[1].getY(), paint);
481       } else {
482         paint.setStrokeWidth(10.0f);
483         for (ResultPoint point : points) {
484           canvas.drawPoint(point.getX(), point.getY(), paint);
485         }
486       }
487     }
488   }
489
490   // Put up our own UI for how to handle the decoded contents.
491   private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
492     statusView.setVisibility(View.GONE);
493     viewfinderView.setVisibility(View.GONE);
494     resultView.setVisibility(View.VISIBLE);
495
496     ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
497     if (barcode == null) {
498       barcodeImageView.setImageResource(R.drawable.zxing_icon);
499     } else {
500       barcodeImageView.setImageBitmap(barcode);
501     }
502     barcodeImageView.setVisibility(View.VISIBLE);
503
504     TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
505     formatTextView.setVisibility(View.VISIBLE);
506     formatTextView.setText(getString(R.string.msg_default_format) + ": " +
507         rawResult.getBarcodeFormat().toString());
508
509     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
510     TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
511     typeTextView.setVisibility(View.VISIBLE);
512     typeTextView.setText(getString(R.string.msg_default_type) + ": " +
513         resultHandler.getType().toString());
514
515     DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
516     String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
517     TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
518     timeTextView.setVisibility(View.VISIBLE);
519     timeTextView.setText(getString(R.string.msg_default_time) + ": " + formattedTime);
520
521     TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
522     CharSequence title = getString(resultHandler.getDisplayTitle());
523     SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
524     styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
525     CharSequence displayContents = resultHandler.getDisplayContents();
526     styled.append(displayContents);
527     contentsTextView.setText(styled);
528
529     int buttonCount = resultHandler.getButtonCount();
530     ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
531     buttonView.requestFocus();
532     for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
533       TextView button = (TextView) buttonView.getChildAt(x);
534       if (x < buttonCount) {
535         button.setVisibility(View.VISIBLE);
536         button.setText(resultHandler.getButtonText(x));
537         button.setOnClickListener(new ResultButtonListener(resultHandler, x));
538       } else {
539         button.setVisibility(View.GONE);
540       }
541     }
542
543     if (copyToClipboard) {
544       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
545       clipboard.setText(displayContents);
546     }
547   }
548
549   // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
550   private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
551     viewfinderView.drawResultBitmap(barcode);
552
553     // Since this message will only be shown for a second, just tell the user what kind of
554     // barcode was found (e.g. contact info) rather than the full contents, which they won't
555     // have time to read.
556     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
557     TextView textView = (TextView) findViewById(R.id.status_text_view);
558     textView.setGravity(Gravity.CENTER);
559     textView.setTextSize(18.0f);
560     textView.setText(getString(resultHandler.getDisplayTitle()));
561
562     statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
563
564     if (copyToClipboard) {
565       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
566       clipboard.setText(resultHandler.getDisplayContents());
567     }
568
569     if (source == Source.NATIVE_APP_INTENT) {
570       // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
571       // the deprecated intent is retired.
572       Intent intent = new Intent(getIntent().getAction());
573       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
574       intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
575       intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
576       Message message = Message.obtain(handler, R.id.return_scan_result);
577       message.obj = intent;
578       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
579     } else if (source == Source.PRODUCT_SEARCH_LINK) {
580       // Reformulate the URL which triggered us into a query, so that the request goes to the same
581       // TLD as the scan URL.
582       Message message = Message.obtain(handler, R.id.launch_product_query);
583       int end = sourceUrl.lastIndexOf("/scan");
584       message.obj = sourceUrl.substring(0, end) + "?q=" +
585           resultHandler.getDisplayContents().toString() + "&source=zxing";
586       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
587     } else if (source == Source.ZXING_LINK) {
588         // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate
589         // with the scanned code. This allows both queries and REST-style URLs to work.
590       Message message = Message.obtain(handler, R.id.launch_product_query);
591       message.obj = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER, resultHandler.getDisplayContents().toString());
592       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
593     }
594   }
595
596   /**
597    * We want the help screen to be shown automatically the first time a new version of the app is
598    * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
599    * it to a value stored as a preference.
600    */
601   private boolean showHelpOnFirstLaunch() {
602     try {
603       PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
604       int currentVersion = info.versionCode;
605       // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
606       // version name here for display in the about box later.
607       this.versionName = info.versionName;
608       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
609       int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
610       if (currentVersion > lastVersion) {
611         prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
612         Intent intent = new Intent(this, HelpActivity.class);
613         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
614         // Show the default page on a clean install, and the what's new page on an upgrade.
615         String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
616         intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
617         startActivity(intent);
618         return true;
619       }
620     } catch (PackageManager.NameNotFoundException e) {
621       Log.w(TAG, e);
622     }
623     return false;
624   }
625
626   /**
627    * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
628    * latency possible.
629    */
630   private void initBeepSound() {
631     if (playBeep && mediaPlayer == null) {
632       // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
633       // so we now play on the music stream.
634       setVolumeControlStream(AudioManager.STREAM_MUSIC);
635       mediaPlayer = new MediaPlayer();
636       mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
637       mediaPlayer.setOnCompletionListener(beepListener);
638
639       AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
640       try {
641         mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
642             file.getLength());
643         file.close();
644         mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
645         mediaPlayer.prepare();
646       } catch (IOException e) {
647         mediaPlayer = null;
648       }
649     }
650   }
651
652   private void playBeepSoundAndVibrate() {
653     if (playBeep && mediaPlayer != null) {
654       mediaPlayer.start();
655     }
656     if (vibrate) {
657       Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
658       vibrator.vibrate(VIBRATE_DURATION);
659     }
660   }
661
662   private void initCamera(SurfaceHolder surfaceHolder) {
663     try {
664       CameraManager.get().openDriver(surfaceHolder);
665     } catch (IOException ioe) {
666       Log.w(TAG, ioe);
667       displayFrameworkBugMessageAndExit();
668       return;
669     } catch (RuntimeException e) {
670       // Barcode Scanner has seen crashes in the wild of this variety:
671       // java.?lang.?RuntimeException: Fail to connect to camera service
672       Log.e(TAG, e.toString());
673       displayFrameworkBugMessageAndExit();
674       return;
675     }
676     if (handler == null) {
677       boolean beginScanning = lastResult == null;
678       handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
679     }
680   }
681
682   private void displayFrameworkBugMessageAndExit() {
683     AlertDialog.Builder builder = new AlertDialog.Builder(this);
684     builder.setTitle(getString(R.string.app_name));
685     builder.setMessage(getString(R.string.msg_camera_framework_bug));
686     builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
687       public void onClick(DialogInterface dialogInterface, int i) {
688         finish();
689       }
690     });
691     builder.show();
692   }
693
694   private void resetStatusView() {
695     resultView.setVisibility(View.GONE);
696     statusView.setVisibility(View.VISIBLE);
697     statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
698     viewfinderView.setVisibility(View.VISIBLE);
699
700     TextView textView = (TextView) findViewById(R.id.status_text_view);
701     textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
702     textView.setTextSize(14.0f);
703     textView.setText(R.string.msg_default_status);
704     lastResult = null;
705   }
706
707   public void drawViewfinder() {
708     viewfinderView.drawViewfinder();
709   }
710
711   /**
712    * When the beep has finished playing, rewind to queue up another one.
713    */
714   private static class BeepListener implements OnCompletionListener {
715     public void onCompletion(MediaPlayer mediaPlayer) {
716       mediaPlayer.seekTo(0);
717     }
718   }
719 }