2 * Copyright (C) 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.client.android;
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
22 import com.google.zxing.client.android.history.HistoryManager;
23 import com.google.zxing.client.android.result.ResultButtonListener;
24 import com.google.zxing.client.android.result.ResultHandler;
25 import com.google.zxing.client.android.result.ResultHandlerFactory;
26 import com.google.zxing.client.android.share.ShareActivity;
28 import android.app.Activity;
29 import android.app.AlertDialog;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.SharedPreferences;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager;
35 import android.content.res.AssetFileDescriptor;
36 import android.content.res.Configuration;
37 import android.graphics.Bitmap;
38 import android.graphics.Canvas;
39 import android.graphics.Paint;
40 import android.graphics.Rect;
41 import android.graphics.drawable.BitmapDrawable;
42 import android.media.AudioManager;
43 import android.media.MediaPlayer;
44 import android.media.MediaPlayer.OnCompletionListener;
45 import android.net.Uri;
46 import android.os.Bundle;
47 import android.os.Handler;
48 import android.os.Message;
49 import android.os.Vibrator;
50 import android.preference.PreferenceManager;
51 import android.text.ClipboardManager;
52 import android.text.SpannableStringBuilder;
53 import android.text.style.UnderlineSpan;
54 import android.util.Log;
55 import android.view.Gravity;
56 import android.view.KeyEvent;
57 import android.view.Menu;
58 import android.view.MenuItem;
59 import android.view.SurfaceHolder;
60 import android.view.SurfaceView;
61 import android.view.View;
62 import android.view.ViewGroup;
63 import android.view.Window;
64 import android.view.WindowManager;
65 import android.widget.ImageView;
66 import android.widget.TextView;
68 import java.io.IOException;
69 import java.util.Vector;
70 import java.util.regex.Pattern;
73 * The barcode reader activity itself. This is loosely based on the CameraPreview
74 * example included in the Android SDK.
76 * @author dswitkin@google.com (Daniel Switkin)
78 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
80 private static final String TAG = "CaptureActivity";
81 private static final Pattern COMMA_PATTERN = Pattern.compile(",");
83 private static final int SHARE_ID = Menu.FIRST;
84 private static final int HISTORY_ID = Menu.FIRST + 1;
85 private static final int SETTINGS_ID = Menu.FIRST + 2;
86 private static final int HELP_ID = Menu.FIRST + 3;
87 private static final int ABOUT_ID = Menu.FIRST + 4;
89 private static final int MAX_RESULT_IMAGE_SIZE = 150;
90 private static final long INTENT_RESULT_DURATION = 1500L;
91 private static final float BEEP_VOLUME = 0.10f;
92 private static final long VIBRATE_DURATION = 200L;
94 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
95 private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
96 private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
97 private static final String ZXING_URL = "http://zxing.appspot.com/scan";
99 static final Vector<BarcodeFormat> PRODUCT_FORMATS;
100 static final Vector<BarcodeFormat> ONE_D_FORMATS;
101 static final Vector<BarcodeFormat> QR_CODE_FORMATS;
102 static final Vector<BarcodeFormat> ALL_FORMATS;
105 PRODUCT_FORMATS = new Vector<BarcodeFormat>(5);
106 PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
107 PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
108 PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
109 PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
110 PRODUCT_FORMATS.add(BarcodeFormat.RSS14);
111 ONE_D_FORMATS = new Vector<BarcodeFormat>(PRODUCT_FORMATS.size() + 3);
112 ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
113 ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
114 ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
115 ONE_D_FORMATS.add(BarcodeFormat.ITF);
116 QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
117 QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
118 ALL_FORMATS = new Vector<BarcodeFormat>(ONE_D_FORMATS.size() + QR_CODE_FORMATS.size());
119 ALL_FORMATS.addAll(ONE_D_FORMATS);
120 ALL_FORMATS.addAll(QR_CODE_FORMATS);
123 private enum Source {
130 private CaptureActivityHandler handler;
132 private ViewfinderView viewfinderView;
133 private View statusView;
134 private View resultView;
135 private MediaPlayer mediaPlayer;
136 private Result lastResult;
137 private boolean hasSurface;
138 private boolean playBeep;
139 private boolean vibrate;
140 private boolean copyToClipboard;
141 private Source source;
142 private String sourceUrl;
143 private Vector<BarcodeFormat> decodeFormats;
144 private String characterSet;
145 private String versionName;
146 private HistoryManager historyManager;
148 private final OnCompletionListener beepListener = new BeepListener();
150 private final DialogInterface.OnClickListener aboutListener =
151 new DialogInterface.OnClickListener() {
152 public void onClick(DialogInterface dialogInterface, int i) {
153 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
154 startActivity(intent);
158 ViewfinderView getViewfinderView() {
159 return viewfinderView;
162 public Handler getHandler() {
167 public void onCreate(Bundle icicle) {
168 super.onCreate(icicle);
170 Window window = getWindow();
171 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
172 setContentView(R.layout.capture);
174 CameraManager.init(getApplication());
175 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
176 resultView = findViewById(R.id.result_view);
177 statusView = findViewById(R.id.status_view);
181 historyManager = new HistoryManager(this);
182 historyManager.trimHistory();
184 showHelpOnFirstLaunch();
188 protected void onResume() {
191 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
192 SurfaceHolder surfaceHolder = surfaceView.getHolder();
194 // The activity was paused but not stopped, so the surface still exists. Therefore
195 // surfaceCreated() won't be called, so init the camera here.
196 initCamera(surfaceHolder);
198 // Install the callback and wait for surfaceCreated() to init the camera.
199 surfaceHolder.addCallback(this);
200 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
203 Intent intent = getIntent();
204 String action = intent == null ? null : intent.getAction();
205 String dataString = intent == null ? null : intent.getDataString();
206 if (intent != null && action != null) {
207 if (action.equals(Intents.Scan.ACTION)) {
208 // Scan the formats the intent requested, and return the result to the calling activity.
209 source = Source.NATIVE_APP_INTENT;
210 decodeFormats = parseDecodeFormats(intent);
212 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
213 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
214 // Scan only products and send the result to mobile Product Search.
215 source = Source.PRODUCT_SEARCH_LINK;
216 sourceUrl = dataString;
217 decodeFormats = PRODUCT_FORMATS;
219 } else if (dataString != null && dataString.equals(ZXING_URL)) {
220 // Scan all formats and handle the results ourselves.
221 // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
222 source = Source.ZXING_LINK;
223 sourceUrl = dataString;
224 decodeFormats = null;
227 // Scan all formats and handle the results ourselves (launched from Home).
228 source = Source.NONE;
229 decodeFormats = null;
232 characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
234 source = Source.NONE;
235 decodeFormats = null;
237 if (lastResult == null) {
242 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
243 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
244 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
245 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
249 private static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
250 String scanFormats = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
251 if (scanFormats != null) {
252 Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
254 for (String format : COMMA_PATTERN.split(scanFormats)) {
255 formats.add(BarcodeFormat.valueOf(format));
257 } catch (IllegalArgumentException iae) {
261 String decodeMode = intent.getStringExtra(Intents.Scan.MODE);
262 if (decodeMode != null) {
263 if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
264 return PRODUCT_FORMATS;
266 if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
267 return QR_CODE_FORMATS;
269 if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
270 return ONE_D_FORMATS;
277 protected void onPause() {
279 if (handler != null) {
280 handler.quitSynchronously();
283 CameraManager.get().closeDriver();
287 public boolean onKeyDown(int keyCode, KeyEvent event) {
288 if (keyCode == KeyEvent.KEYCODE_BACK) {
289 if (source == Source.NATIVE_APP_INTENT) {
290 setResult(RESULT_CANCELED);
293 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
295 if (handler != null) {
296 handler.sendEmptyMessage(R.id.restart_preview);
300 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
301 // Handle these events so they don't launch the Camera app
304 return super.onKeyDown(keyCode, event);
308 public boolean onCreateOptionsMenu(Menu menu) {
309 super.onCreateOptionsMenu(menu);
310 menu.add(0, SHARE_ID, 0, R.string.menu_share)
311 .setIcon(android.R.drawable.ic_menu_share);
312 menu.add(0, HISTORY_ID, 0, R.string.menu_history)
313 .setIcon(android.R.drawable.ic_menu_recent_history);
314 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
315 .setIcon(android.R.drawable.ic_menu_preferences);
316 menu.add(0, HELP_ID, 0, R.string.menu_help)
317 .setIcon(android.R.drawable.ic_menu_help);
318 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
319 .setIcon(android.R.drawable.ic_menu_info_details);
323 // Don't display the share menu item if the result overlay is showing.
325 public boolean onPrepareOptionsMenu(Menu menu) {
326 super.onPrepareOptionsMenu(menu);
327 menu.findItem(SHARE_ID).setVisible(lastResult == null);
332 public boolean onOptionsItemSelected(MenuItem item) {
333 switch (item.getItemId()) {
335 Intent intent = new Intent(Intent.ACTION_VIEW);
336 intent.setClassName(this, ShareActivity.class.getName());
337 startActivity(intent);
341 AlertDialog historyAlert = historyManager.buildAlert();
346 Intent intent = new Intent(Intent.ACTION_VIEW);
347 intent.setClassName(this, PreferencesActivity.class.getName());
348 startActivity(intent);
352 Intent intent = new Intent(Intent.ACTION_VIEW);
353 intent.setClassName(this, HelpActivity.class.getName());
354 startActivity(intent);
358 AlertDialog.Builder builder = new AlertDialog.Builder(this);
359 builder.setTitle(getString(R.string.title_about) + versionName);
360 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
361 builder.setIcon(R.drawable.zxing_icon);
362 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
363 builder.setNegativeButton(R.string.button_cancel, null);
367 return super.onOptionsItemSelected(item);
371 public void onConfigurationChanged(Configuration config) {
372 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
373 super.onConfigurationChanged(config);
376 public void surfaceCreated(SurfaceHolder holder) {
383 public void surfaceDestroyed(SurfaceHolder holder) {
387 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
392 * A valid barcode has been found, so give an indication of success and show the results.
394 * @param rawResult The contents of the barcode.
395 * @param barcode A greyscale bitmap of the camera data which was decoded.
397 public void handleDecode(Result rawResult, Bitmap barcode) {
398 lastResult = rawResult;
399 historyManager.addHistoryItem(rawResult);
400 if (barcode == null) {
401 // This is from history -- no saved barcode
402 handleDecodeInternally(rawResult, null);
404 playBeepSoundAndVibrate();
405 drawResultPoints(barcode, rawResult);
407 case NATIVE_APP_INTENT:
408 case PRODUCT_SEARCH_LINK:
409 handleDecodeExternally(rawResult, barcode);
413 handleDecodeInternally(rawResult, barcode);
420 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
422 * @param barcode A bitmap of the captured image.
423 * @param rawResult The decoded results which contains the points to draw.
425 private void drawResultPoints(Bitmap barcode, Result rawResult) {
426 ResultPoint[] points = rawResult.getResultPoints();
427 if (points != null && points.length > 0) {
428 Canvas canvas = new Canvas(barcode);
429 Paint paint = new Paint();
430 paint.setColor(getResources().getColor(R.color.result_image_border));
431 paint.setStrokeWidth(3.0f);
432 paint.setStyle(Paint.Style.STROKE);
433 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
434 canvas.drawRect(border, paint);
436 paint.setColor(getResources().getColor(R.color.result_points));
437 if (points.length == 2) {
438 paint.setStrokeWidth(4.0f);
439 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
440 points[1].getY(), paint);
442 paint.setStrokeWidth(10.0f);
443 for (ResultPoint point : points) {
444 canvas.drawPoint(point.getX(), point.getY(), paint);
450 // Put up our own UI for how to handle the decoded contents.
451 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
452 statusView.setVisibility(View.GONE);
453 viewfinderView.setVisibility(View.GONE);
454 resultView.setVisibility(View.VISIBLE);
456 if (barcode == null) {
457 barcode = ((BitmapDrawable) getResources().getDrawable(R.drawable.unknown_barcode)).getBitmap();
459 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
460 barcodeImageView.setVisibility(View.VISIBLE);
461 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
462 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
463 barcodeImageView.setImageBitmap(barcode);
465 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
466 formatTextView.setVisibility(View.VISIBLE);
467 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
468 rawResult.getBarcodeFormat().toString());
470 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
471 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
472 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
473 resultHandler.getType().toString());
475 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
476 CharSequence title = getString(resultHandler.getDisplayTitle());
477 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
478 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
479 CharSequence displayContents = resultHandler.getDisplayContents();
480 styled.append(displayContents);
481 contentsTextView.setText(styled);
483 int buttonCount = resultHandler.getButtonCount();
484 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
485 buttonView.requestFocus();
486 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
487 TextView button = (TextView) buttonView.getChildAt(x);
488 if (x < buttonCount) {
489 button.setVisibility(View.VISIBLE);
490 button.setText(resultHandler.getButtonText(x));
491 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
493 button.setVisibility(View.GONE);
497 if (copyToClipboard) {
498 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
499 clipboard.setText(displayContents);
503 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
504 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
505 viewfinderView.drawResultBitmap(barcode);
507 // Since this message will only be shown for a second, just tell the user what kind of
508 // barcode was found (e.g. contact info) rather than the full contents, which they won't
509 // have time to read.
510 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
511 TextView textView = (TextView) findViewById(R.id.status_text_view);
512 textView.setGravity(Gravity.CENTER);
513 textView.setTextSize(18.0f);
514 textView.setText(getString(resultHandler.getDisplayTitle()));
516 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
518 if (copyToClipboard) {
519 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
520 clipboard.setText(resultHandler.getDisplayContents());
523 if (source == Source.NATIVE_APP_INTENT) {
524 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
525 // the deprecated intent is retired.
526 Intent intent = new Intent(getIntent().getAction());
527 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
528 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
529 Message message = Message.obtain(handler, R.id.return_scan_result);
530 message.obj = intent;
531 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
532 } else if (source == Source.PRODUCT_SEARCH_LINK) {
533 // Reformulate the URL which triggered us into a query, so that the request goes to the same
534 // TLD as the scan URL.
535 Message message = Message.obtain(handler, R.id.launch_product_query);
536 int end = sourceUrl.lastIndexOf("/scan");
537 message.obj = sourceUrl.substring(0, end) + "?q=" +
538 resultHandler.getDisplayContents().toString() + "&source=zxing";
539 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
544 * We want the help screen to be shown automatically the first time a new version of the app is
545 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
546 * it to a value stored as a preference.
548 private boolean showHelpOnFirstLaunch() {
550 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
551 int currentVersion = info.versionCode;
552 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
553 // version name here for display in the about box later.
554 this.versionName = info.versionName;
555 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
556 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
557 if (currentVersion > lastVersion) {
558 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
559 Intent intent = new Intent(Intent.ACTION_VIEW);
560 intent.setClassName(this, HelpActivity.class.getName());
561 startActivity(intent);
564 } catch (PackageManager.NameNotFoundException e) {
571 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
574 private void initBeepSound() {
575 if (playBeep && mediaPlayer == null) {
576 // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
577 // so we now play on the music stream.
578 setVolumeControlStream(AudioManager.STREAM_MUSIC);
579 mediaPlayer = new MediaPlayer();
580 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
581 mediaPlayer.setOnCompletionListener(beepListener);
583 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
585 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
588 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
589 mediaPlayer.prepare();
590 } catch (IOException e) {
596 private void playBeepSoundAndVibrate() {
597 if (playBeep && mediaPlayer != null) {
601 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
602 vibrator.vibrate(VIBRATE_DURATION);
606 private void initCamera(SurfaceHolder surfaceHolder) {
608 CameraManager.get().openDriver(surfaceHolder);
609 } catch (IOException ioe) {
611 displayFrameworkBugMessageAndExit();
613 } catch (RuntimeException e) {
614 // Barcode Scanner has seen crashes in the wild of this variety:
615 // java.?lang.?RuntimeException: Fail to connect to camera service
616 Log.e(TAG, e.toString());
617 displayFrameworkBugMessageAndExit();
620 if (handler == null) {
621 boolean beginScanning = lastResult == null;
622 handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
626 private void displayFrameworkBugMessageAndExit() {
627 AlertDialog.Builder builder = new AlertDialog.Builder(this);
628 builder.setTitle(getString(R.string.app_name));
629 builder.setMessage(getString(R.string.msg_camera_framework_bug));
630 builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
631 public void onClick(DialogInterface dialogInterface, int i) {
638 private void resetStatusView() {
639 resultView.setVisibility(View.GONE);
640 statusView.setVisibility(View.VISIBLE);
641 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
642 viewfinderView.setVisibility(View.VISIBLE);
644 TextView textView = (TextView) findViewById(R.id.status_text_view);
645 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
646 textView.setTextSize(14.0f);
647 textView.setText(R.string.msg_default_status);
651 public void drawViewfinder() {
652 viewfinderView.drawViewfinder();
656 * When the beep has finished playing, rewind to queue up another one.
658 private static class BeepListener implements OnCompletionListener {
659 public void onCompletion(MediaPlayer mediaPlayer) {
660 mediaPlayer.seekTo(0);