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