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