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 versionName;
145 private HistoryManager historyManager;
147 private final OnCompletionListener beepListener = new BeepListener();
149 private final DialogInterface.OnClickListener aboutListener =
150 new DialogInterface.OnClickListener() {
151 public void onClick(DialogInterface dialogInterface, int i) {
152 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
153 startActivity(intent);
157 ViewfinderView getViewfinderView() {
158 return viewfinderView;
161 public Handler getHandler() {
166 public void onCreate(Bundle icicle) {
167 super.onCreate(icicle);
169 Window window = getWindow();
170 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
171 setContentView(R.layout.capture);
173 CameraManager.init(getApplication());
174 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
175 resultView = findViewById(R.id.result_view);
176 statusView = findViewById(R.id.status_view);
180 historyManager = new HistoryManager(this);
181 historyManager.trimHistory();
183 showHelpOnFirstLaunch();
187 protected void onResume() {
190 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
191 SurfaceHolder surfaceHolder = surfaceView.getHolder();
193 // The activity was paused but not stopped, so the surface still exists. Therefore
194 // surfaceCreated() won't be called, so init the camera here.
195 initCamera(surfaceHolder);
197 // Install the callback and wait for surfaceCreated() to init the camera.
198 surfaceHolder.addCallback(this);
199 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
202 Intent intent = getIntent();
203 String action = intent == null ? null : intent.getAction();
204 String dataString = intent == null ? null : intent.getDataString();
205 if (intent != null && action != null) {
206 if (action.equals(Intents.Scan.ACTION)) {
207 // Scan the formats the intent requested, and return the result to the calling activity.
208 source = Source.NATIVE_APP_INTENT;
209 decodeFormats = parseDecodeFormats(intent);
211 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
212 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
213 // Scan only products and send the result to mobile Product Search.
214 source = Source.PRODUCT_SEARCH_LINK;
215 sourceUrl = dataString;
216 decodeFormats = PRODUCT_FORMATS;
218 } else if (dataString != null && dataString.equals(ZXING_URL)) {
219 // Scan all formats and handle the results ourselves.
220 // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
221 source = Source.ZXING_LINK;
222 sourceUrl = dataString;
223 decodeFormats = null;
226 // Scan all formats and handle the results ourselves (launched from Home).
227 source = Source.NONE;
228 decodeFormats = null;
232 source = Source.NONE;
233 decodeFormats = null;
234 if (lastResult == null) {
239 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
240 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
241 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
242 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
246 private static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
247 String scanFormats = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
248 if (scanFormats != null) {
249 Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
251 for (String format : COMMA_PATTERN.split(scanFormats)) {
252 formats.add(BarcodeFormat.valueOf(format));
254 } catch (IllegalArgumentException iae) {
258 String decodeMode = intent.getStringExtra(Intents.Scan.MODE);
259 if (decodeMode != null) {
260 if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
261 return PRODUCT_FORMATS;
263 if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
264 return QR_CODE_FORMATS;
266 if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
267 return ONE_D_FORMATS;
274 protected void onPause() {
276 if (handler != null) {
277 handler.quitSynchronously();
280 CameraManager.get().closeDriver();
284 public boolean onKeyDown(int keyCode, KeyEvent event) {
285 if (keyCode == KeyEvent.KEYCODE_BACK) {
286 if (source == Source.NATIVE_APP_INTENT) {
287 setResult(RESULT_CANCELED);
290 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
292 if (handler != null) {
293 handler.sendEmptyMessage(R.id.restart_preview);
297 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
298 // Handle these events so they don't launch the Camera app
301 return super.onKeyDown(keyCode, event);
305 public boolean onCreateOptionsMenu(Menu menu) {
306 super.onCreateOptionsMenu(menu);
307 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
308 menu.add(0, HISTORY_ID, 0, R.string.menu_history)
309 .setIcon(android.R.drawable.ic_menu_recent_history);
310 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
311 .setIcon(android.R.drawable.ic_menu_preferences);
312 menu.add(0, HELP_ID, 0, R.string.menu_help)
313 .setIcon(android.R.drawable.ic_menu_help);
314 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
315 .setIcon(android.R.drawable.ic_menu_info_details);
319 // Don't display the share menu item if the result overlay is showing.
321 public boolean onPrepareOptionsMenu(Menu menu) {
322 super.onPrepareOptionsMenu(menu);
323 menu.findItem(SHARE_ID).setVisible(lastResult == null);
328 public boolean onOptionsItemSelected(MenuItem item) {
329 switch (item.getItemId()) {
331 Intent intent = new Intent(Intent.ACTION_VIEW);
332 intent.setClassName(this, ShareActivity.class.getName());
333 startActivity(intent);
337 AlertDialog historyAlert = historyManager.buildAlert();
342 Intent intent = new Intent(Intent.ACTION_VIEW);
343 intent.setClassName(this, PreferencesActivity.class.getName());
344 startActivity(intent);
348 Intent intent = new Intent(Intent.ACTION_VIEW);
349 intent.setClassName(this, HelpActivity.class.getName());
350 startActivity(intent);
354 AlertDialog.Builder builder = new AlertDialog.Builder(this);
355 builder.setTitle(getString(R.string.title_about) + versionName);
356 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
357 builder.setIcon(R.drawable.zxing_icon);
358 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
359 builder.setNegativeButton(R.string.button_cancel, null);
363 return super.onOptionsItemSelected(item);
367 public void onConfigurationChanged(Configuration config) {
368 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
369 super.onConfigurationChanged(config);
372 public void surfaceCreated(SurfaceHolder holder) {
379 public void surfaceDestroyed(SurfaceHolder holder) {
383 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
388 * A valid barcode has been found, so give an indication of success and show the results.
390 * @param rawResult The contents of the barcode.
391 * @param barcode A greyscale bitmap of the camera data which was decoded.
393 public void handleDecode(Result rawResult, Bitmap barcode) {
394 lastResult = rawResult;
395 historyManager.addHistoryItem(rawResult);
396 if (barcode == null) {
397 // This is from history -- no saved barcode
398 handleDecodeInternally(rawResult, null);
400 playBeepSoundAndVibrate();
401 drawResultPoints(barcode, rawResult);
403 case NATIVE_APP_INTENT:
404 case PRODUCT_SEARCH_LINK:
405 handleDecodeExternally(rawResult, barcode);
409 handleDecodeInternally(rawResult, barcode);
416 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
418 * @param barcode A bitmap of the captured image.
419 * @param rawResult The decoded results which contains the points to draw.
421 private void drawResultPoints(Bitmap barcode, Result rawResult) {
422 ResultPoint[] points = rawResult.getResultPoints();
423 if (points != null && points.length > 0) {
424 Canvas canvas = new Canvas(barcode);
425 Paint paint = new Paint();
426 paint.setColor(getResources().getColor(R.color.result_image_border));
427 paint.setStrokeWidth(3.0f);
428 paint.setStyle(Paint.Style.STROKE);
429 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
430 canvas.drawRect(border, paint);
432 paint.setColor(getResources().getColor(R.color.result_points));
433 if (points.length == 2) {
434 paint.setStrokeWidth(4.0f);
435 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
436 points[1].getY(), paint);
438 paint.setStrokeWidth(10.0f);
439 for (ResultPoint point : points) {
440 canvas.drawPoint(point.getX(), point.getY(), paint);
446 // Put up our own UI for how to handle the decoded contents.
447 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
448 statusView.setVisibility(View.GONE);
449 viewfinderView.setVisibility(View.GONE);
450 resultView.setVisibility(View.VISIBLE);
452 if (barcode == null) {
453 barcode = ((BitmapDrawable) getResources().getDrawable(R.drawable.unknown_barcode)).getBitmap();
455 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
456 barcodeImageView.setVisibility(View.VISIBLE);
457 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
458 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
459 barcodeImageView.setImageBitmap(barcode);
461 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
462 formatTextView.setVisibility(View.VISIBLE);
463 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
464 rawResult.getBarcodeFormat().toString());
466 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
467 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
468 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
469 resultHandler.getType().toString());
471 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
472 CharSequence title = getString(resultHandler.getDisplayTitle());
473 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
474 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
475 CharSequence displayContents = resultHandler.getDisplayContents();
476 styled.append(displayContents);
477 contentsTextView.setText(styled);
479 int buttonCount = resultHandler.getButtonCount();
480 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
481 buttonView.requestFocus();
482 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
483 TextView button = (TextView) buttonView.getChildAt(x);
484 if (x < buttonCount) {
485 button.setVisibility(View.VISIBLE);
486 button.setText(resultHandler.getButtonText(x));
487 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
489 button.setVisibility(View.GONE);
493 if (copyToClipboard) {
494 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
495 clipboard.setText(displayContents);
499 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
500 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
501 viewfinderView.drawResultBitmap(barcode);
503 // Since this message will only be shown for a second, just tell the user what kind of
504 // barcode was found (e.g. contact info) rather than the full contents, which they won't
505 // have time to read.
506 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
507 TextView textView = (TextView) findViewById(R.id.status_text_view);
508 textView.setGravity(Gravity.CENTER);
509 textView.setTextSize(18.0f);
510 textView.setText(getString(resultHandler.getDisplayTitle()));
512 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
514 if (copyToClipboard) {
515 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
516 clipboard.setText(resultHandler.getDisplayContents());
519 if (source == Source.NATIVE_APP_INTENT) {
520 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
521 // the deprecated intent is retired.
522 Intent intent = new Intent(getIntent().getAction());
523 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
524 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
525 Message message = Message.obtain(handler, R.id.return_scan_result);
526 message.obj = intent;
527 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
528 } else if (source == Source.PRODUCT_SEARCH_LINK) {
529 // Reformulate the URL which triggered us into a query, so that the request goes to the same
530 // TLD as the scan URL.
531 Message message = Message.obtain(handler, R.id.launch_product_query);
532 int end = sourceUrl.lastIndexOf("/scan");
533 message.obj = sourceUrl.substring(0, end) + "?q=" +
534 resultHandler.getDisplayContents().toString() + "&source=zxing";
535 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
540 * We want the help screen to be shown automatically the first time a new version of the app is
541 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
542 * it to a value stored as a preference.
544 private boolean showHelpOnFirstLaunch() {
546 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
547 int currentVersion = info.versionCode;
548 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
549 // version name here for display in the about box later.
550 this.versionName = info.versionName;
551 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
552 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
553 if (currentVersion > lastVersion) {
554 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
555 Intent intent = new Intent(Intent.ACTION_VIEW);
556 intent.setClassName(this, HelpActivity.class.getName());
557 startActivity(intent);
560 } catch (PackageManager.NameNotFoundException e) {
567 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
570 private void initBeepSound() {
571 if (playBeep && mediaPlayer == null) {
572 // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
573 // so we now play on the music stream.
574 setVolumeControlStream(AudioManager.STREAM_MUSIC);
575 mediaPlayer = new MediaPlayer();
576 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
577 mediaPlayer.setOnCompletionListener(beepListener);
579 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
581 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
584 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
585 mediaPlayer.prepare();
586 } catch (IOException e) {
592 private void playBeepSoundAndVibrate() {
593 if (playBeep && mediaPlayer != null) {
597 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
598 vibrator.vibrate(VIBRATE_DURATION);
602 private void initCamera(SurfaceHolder surfaceHolder) {
604 CameraManager.get().openDriver(surfaceHolder);
605 } catch (IOException ioe) {
607 displayFrameworkBugMessageAndExit();
609 } catch (RuntimeException e) {
610 // Barcode Scanner has seen crashes in the wild of this variety:
611 // java.?lang.?RuntimeException: Fail to connect to camera service
612 Log.e(TAG, e.toString());
613 displayFrameworkBugMessageAndExit();
616 if (handler == null) {
617 boolean beginScanning = lastResult == null;
618 handler = new CaptureActivityHandler(this, decodeFormats, beginScanning);
622 private void displayFrameworkBugMessageAndExit() {
623 AlertDialog.Builder builder = new AlertDialog.Builder(this);
624 builder.setTitle(getString(R.string.app_name));
625 builder.setMessage(getString(R.string.msg_camera_framework_bug));
626 builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
627 public void onClick(DialogInterface dialogInterface, int i) {
634 private void resetStatusView() {
635 resultView.setVisibility(View.GONE);
636 statusView.setVisibility(View.VISIBLE);
637 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
638 viewfinderView.setVisibility(View.VISIBLE);
640 TextView textView = (TextView) findViewById(R.id.status_text_view);
641 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
642 textView.setTextSize(14.0f);
643 textView.setText(R.string.msg_default_status);
647 public void drawViewfinder() {
648 viewfinderView.drawViewfinder();
652 * When the beep has finished playing, rewind to queue up another one.
654 private static class BeepListener implements OnCompletionListener {
655 public void onCompletion(MediaPlayer mediaPlayer) {
656 mediaPlayer.seekTo(0);