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