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