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