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