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