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