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.Result;
20 import com.google.zxing.ResultPoint;
21 import com.google.zxing.client.android.history.HistoryManager;
22 import com.google.zxing.client.android.result.ResultButtonListener;
23 import com.google.zxing.client.android.result.ResultHandler;
24 import com.google.zxing.client.android.result.ResultHandlerFactory;
25 import com.google.zxing.client.android.share.ShareActivity;
27 import android.app.Activity;
28 import android.app.AlertDialog;
29 import android.content.DialogInterface;
30 import android.content.Intent;
31 import android.content.SharedPreferences;
32 import android.content.pm.PackageInfo;
33 import android.content.pm.PackageManager;
34 import android.content.res.AssetFileDescriptor;
35 import android.content.res.Configuration;
36 import android.graphics.Bitmap;
37 import android.graphics.Canvas;
38 import android.graphics.Paint;
39 import android.graphics.Rect;
40 import android.graphics.drawable.BitmapDrawable;
41 import android.media.AudioManager;
42 import android.media.MediaPlayer;
43 import android.media.MediaPlayer.OnCompletionListener;
44 import android.net.Uri;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.os.Message;
48 import android.os.Vibrator;
49 import android.preference.PreferenceManager;
50 import android.text.ClipboardManager;
51 import android.text.SpannableStringBuilder;
52 import android.text.style.UnderlineSpan;
53 import android.util.Log;
54 import android.view.Gravity;
55 import android.view.KeyEvent;
56 import android.view.Menu;
57 import android.view.MenuItem;
58 import android.view.SurfaceHolder;
59 import android.view.SurfaceView;
60 import android.view.View;
61 import android.view.ViewGroup;
62 import android.view.Window;
63 import android.view.WindowManager;
64 import android.widget.ImageView;
65 import android.widget.TextView;
67 import java.io.IOException;
70 * The barcode reader activity itself. This is loosely based on the CameraPreview
71 * example included in the Android SDK.
73 * @author dswitkin@google.com (Daniel Switkin)
75 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
76 private static final String TAG = "CaptureActivity";
78 private static final int SHARE_ID = Menu.FIRST;
79 private static final int HISTORY_ID = Menu.FIRST + 1;
80 private static final int SETTINGS_ID = Menu.FIRST + 2;
81 private static final int HELP_ID = Menu.FIRST + 3;
82 private static final int ABOUT_ID = Menu.FIRST + 4;
84 private static final int MAX_RESULT_IMAGE_SIZE = 150;
85 private static final long INTENT_RESULT_DURATION = 1500L;
86 private static final float BEEP_VOLUME = 0.10f;
87 private static final long VIBRATE_DURATION = 200L;
89 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
90 private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
91 private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
92 private static final String ZXING_URL = "http://zxing.appspot.com/scan";
101 private CaptureActivityHandler handler;
103 private ViewfinderView viewfinderView;
104 private View statusView;
105 private View resultView;
106 private MediaPlayer mediaPlayer;
107 private Result lastResult;
108 private boolean hasSurface;
109 private boolean playBeep;
110 private boolean vibrate;
111 private boolean copyToClipboard;
112 private Source source;
113 private String sourceUrl;
114 private String decodeMode;
115 private String versionName;
116 private HistoryManager historyManager;
118 private final OnCompletionListener beepListener = new BeepListener();
120 private final DialogInterface.OnClickListener aboutListener =
121 new DialogInterface.OnClickListener() {
122 public void onClick(DialogInterface dialogInterface, int i) {
123 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
124 startActivity(intent);
128 ViewfinderView getViewfinderView() {
129 return viewfinderView;
132 public Handler getHandler() {
137 public void onCreate(Bundle icicle) {
138 super.onCreate(icicle);
140 Window window = getWindow();
141 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
142 setContentView(R.layout.capture);
144 CameraManager.init(getApplication());
145 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
146 resultView = findViewById(R.id.result_view);
147 statusView = findViewById(R.id.status_view);
151 historyManager = new HistoryManager(this);
152 historyManager.trimHistory();
154 showHelpOnFirstLaunch();
158 protected void onResume() {
161 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
162 SurfaceHolder surfaceHolder = surfaceView.getHolder();
164 // The activity was paused but not stopped, so the surface still exists. Therefore
165 // surfaceCreated() won't be called, so init the camera here.
166 initCamera(surfaceHolder);
168 // Install the callback and wait for surfaceCreated() to init the camera.
169 surfaceHolder.addCallback(this);
170 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
173 Intent intent = getIntent();
174 String action = intent == null ? null : intent.getAction();
175 String dataString = intent == null ? null : intent.getDataString();
176 if (intent != null && action != null) {
177 if (action.equals(Intents.Scan.ACTION)) {
178 // Scan the formats the intent requested, and return the result to the calling activity.
179 source = Source.NATIVE_APP_INTENT;
180 decodeMode = intent.getStringExtra(Intents.Scan.MODE);
182 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
183 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
184 // Scan only products and send the result to mobile Product Search.
185 source = Source.PRODUCT_SEARCH_LINK;
186 sourceUrl = dataString;
187 decodeMode = Intents.Scan.PRODUCT_MODE;
189 } else if (dataString != null && dataString.equals(ZXING_URL)) {
190 // Scan all formats and handle the results ourselves.
191 // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
192 source = Source.ZXING_LINK;
193 sourceUrl = dataString;
197 // Scan all formats and handle the results ourselves (launched from Home).
198 source = Source.NONE;
203 source = Source.NONE;
205 if (lastResult == null) {
210 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
211 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
212 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
213 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
218 protected void onPause() {
220 if (handler != null) {
221 handler.quitSynchronously();
224 CameraManager.get().closeDriver();
228 public boolean onKeyDown(int keyCode, KeyEvent event) {
229 if (keyCode == KeyEvent.KEYCODE_BACK) {
230 if (source == Source.NATIVE_APP_INTENT) {
231 setResult(RESULT_CANCELED);
234 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
236 if (handler != null) {
237 handler.sendEmptyMessage(R.id.restart_preview);
241 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
242 // Handle these events so they don't launch the Camera app
245 return super.onKeyDown(keyCode, event);
249 public boolean onCreateOptionsMenu(Menu menu) {
250 super.onCreateOptionsMenu(menu);
251 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
252 menu.add(0, HISTORY_ID, 0, R.string.menu_history)
253 .setIcon(android.R.drawable.ic_menu_recent_history);
254 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
255 .setIcon(android.R.drawable.ic_menu_preferences);
256 menu.add(0, HELP_ID, 0, R.string.menu_help)
257 .setIcon(android.R.drawable.ic_menu_help);
258 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
259 .setIcon(android.R.drawable.ic_menu_info_details);
263 // Don't display the share menu item if the result overlay is showing.
265 public boolean onPrepareOptionsMenu(Menu menu) {
266 super.onPrepareOptionsMenu(menu);
267 menu.findItem(SHARE_ID).setVisible(lastResult == null);
272 public boolean onOptionsItemSelected(MenuItem item) {
273 switch (item.getItemId()) {
275 Intent intent = new Intent(Intent.ACTION_VIEW);
276 intent.setClassName(this, ShareActivity.class.getName());
277 startActivity(intent);
281 AlertDialog historyAlert = historyManager.buildAlert();
286 Intent intent = new Intent(Intent.ACTION_VIEW);
287 intent.setClassName(this, PreferencesActivity.class.getName());
288 startActivity(intent);
292 Intent intent = new Intent(Intent.ACTION_VIEW);
293 intent.setClassName(this, HelpActivity.class.getName());
294 startActivity(intent);
298 AlertDialog.Builder builder = new AlertDialog.Builder(this);
299 builder.setTitle(getString(R.string.title_about) + versionName);
300 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
301 builder.setIcon(R.drawable.zxing_icon);
302 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
303 builder.setNegativeButton(R.string.button_cancel, null);
307 return super.onOptionsItemSelected(item);
311 public void onConfigurationChanged(Configuration config) {
312 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
313 super.onConfigurationChanged(config);
316 public void surfaceCreated(SurfaceHolder holder) {
323 public void surfaceDestroyed(SurfaceHolder holder) {
327 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
332 * A valid barcode has been found, so give an indication of success and show the results.
334 * @param rawResult The contents of the barcode.
335 * @param barcode A greyscale bitmap of the camera data which was decoded.
337 public void handleDecode(Result rawResult, Bitmap barcode) {
338 lastResult = rawResult;
339 historyManager.addHistoryItem(rawResult);
340 if (barcode == null) {
341 // This is from history -- no saved barcode
342 handleDecodeInternally(rawResult, null);
344 playBeepSoundAndVibrate();
345 drawResultPoints(barcode, rawResult);
347 case NATIVE_APP_INTENT:
348 case PRODUCT_SEARCH_LINK:
349 handleDecodeExternally(rawResult, barcode);
353 handleDecodeInternally(rawResult, barcode);
360 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
362 * @param barcode A bitmap of the captured image.
363 * @param rawResult The decoded results which contains the points to draw.
365 private void drawResultPoints(Bitmap barcode, Result rawResult) {
366 ResultPoint[] points = rawResult.getResultPoints();
367 if (points != null && points.length > 0) {
368 Canvas canvas = new Canvas(barcode);
369 Paint paint = new Paint();
370 paint.setColor(getResources().getColor(R.color.result_image_border));
371 paint.setStrokeWidth(3.0f);
372 paint.setStyle(Paint.Style.STROKE);
373 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
374 canvas.drawRect(border, paint);
376 paint.setColor(getResources().getColor(R.color.result_points));
377 if (points.length == 2) {
378 paint.setStrokeWidth(4.0f);
379 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
380 points[1].getY(), paint);
382 paint.setStrokeWidth(10.0f);
383 for (ResultPoint point : points) {
384 canvas.drawPoint(point.getX(), point.getY(), paint);
390 // Put up our own UI for how to handle the decoded contents.
391 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
392 statusView.setVisibility(View.GONE);
393 viewfinderView.setVisibility(View.GONE);
394 resultView.setVisibility(View.VISIBLE);
396 if (barcode == null) {
397 barcode = ((BitmapDrawable) getResources().getDrawable(R.drawable.unknown_barcode)).getBitmap();
399 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
400 barcodeImageView.setVisibility(View.VISIBLE);
401 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
402 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
403 barcodeImageView.setImageBitmap(barcode);
405 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
406 formatTextView.setVisibility(View.VISIBLE);
407 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
408 rawResult.getBarcodeFormat().toString());
410 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
411 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
412 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
413 resultHandler.getType().toString());
415 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
416 CharSequence title = getString(resultHandler.getDisplayTitle());
417 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
418 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
419 CharSequence displayContents = resultHandler.getDisplayContents();
420 styled.append(displayContents);
421 contentsTextView.setText(styled);
423 int buttonCount = resultHandler.getButtonCount();
424 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
425 buttonView.requestFocus();
426 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
427 TextView button = (TextView) buttonView.getChildAt(x);
428 if (x < buttonCount) {
429 button.setVisibility(View.VISIBLE);
430 button.setText(resultHandler.getButtonText(x));
431 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
433 button.setVisibility(View.GONE);
437 if (copyToClipboard) {
438 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
439 clipboard.setText(displayContents);
443 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
444 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
445 viewfinderView.drawResultBitmap(barcode);
447 // Since this message will only be shown for a second, just tell the user what kind of
448 // barcode was found (e.g. contact info) rather than the full contents, which they won't
449 // have time to read.
450 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
451 TextView textView = (TextView) findViewById(R.id.status_text_view);
452 textView.setGravity(Gravity.CENTER);
453 textView.setTextSize(18.0f);
454 textView.setText(getString(resultHandler.getDisplayTitle()));
456 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
458 if (copyToClipboard) {
459 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
460 clipboard.setText(resultHandler.getDisplayContents());
463 if (source == Source.NATIVE_APP_INTENT) {
464 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
465 // the deprecated intent is retired.
466 Intent intent = new Intent(getIntent().getAction());
467 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
468 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
469 Message message = Message.obtain(handler, R.id.return_scan_result);
470 message.obj = intent;
471 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
472 } else if (source == Source.PRODUCT_SEARCH_LINK) {
473 // Reformulate the URL which triggered us into a query, so that the request goes to the same
474 // TLD as the scan URL.
475 Message message = Message.obtain(handler, R.id.launch_product_query);
476 int end = sourceUrl.lastIndexOf("/scan");
477 message.obj = sourceUrl.substring(0, end) + "?q=" +
478 resultHandler.getDisplayContents().toString() + "&source=zxing";
479 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
484 * We want the help screen to be shown automatically the first time a new version of the app is
485 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
486 * it to a value stored as a preference.
488 private boolean showHelpOnFirstLaunch() {
490 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
491 int currentVersion = info.versionCode;
492 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
493 // version name here for display in the about box later.
494 this.versionName = info.versionName;
495 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
496 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
497 if (currentVersion > lastVersion) {
498 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
499 Intent intent = new Intent(Intent.ACTION_VIEW);
500 intent.setClassName(this, HelpActivity.class.getName());
501 startActivity(intent);
504 } catch (PackageManager.NameNotFoundException e) {
511 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
514 private void initBeepSound() {
515 if (playBeep && mediaPlayer == null) {
516 // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
517 // so we now play on the music stream.
518 setVolumeControlStream(AudioManager.STREAM_MUSIC);
519 mediaPlayer = new MediaPlayer();
520 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
521 mediaPlayer.setOnCompletionListener(beepListener);
523 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
525 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
528 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
529 mediaPlayer.prepare();
530 } catch (IOException e) {
536 private void playBeepSoundAndVibrate() {
537 if (playBeep && mediaPlayer != null) {
541 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
542 vibrator.vibrate(VIBRATE_DURATION);
546 private void initCamera(SurfaceHolder surfaceHolder) {
548 CameraManager.get().openDriver(surfaceHolder);
549 } catch (IOException ioe) {
551 displayFrameworkBugMessageAndExit();
553 } catch (RuntimeException e) {
554 // Barcode Scanner has seen crashes in the wild of this variety:
555 // java.?lang.?RuntimeException: Fail to connect to camera service
556 Log.e(TAG, e.toString());
557 displayFrameworkBugMessageAndExit();
560 if (handler == null) {
561 boolean beginScanning = lastResult == null;
562 handler = new CaptureActivityHandler(this, decodeMode, beginScanning);
566 private void displayFrameworkBugMessageAndExit() {
567 AlertDialog.Builder builder = new AlertDialog.Builder(this);
568 builder.setTitle(getString(R.string.app_name));
569 builder.setMessage(getString(R.string.msg_camera_framework_bug));
570 builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
571 public void onClick(DialogInterface dialogInterface, int i) {
578 private void resetStatusView() {
579 resultView.setVisibility(View.GONE);
580 statusView.setVisibility(View.VISIBLE);
581 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
582 viewfinderView.setVisibility(View.VISIBLE);
584 TextView textView = (TextView) findViewById(R.id.status_text_view);
585 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
586 textView.setTextSize(14.0f);
587 textView.setText(R.string.msg_default_status);
591 public void drawViewfinder() {
592 viewfinderView.drawViewfinder();
596 * When the beep has finished playing, rewind to queue up another one.
598 private static class BeepListener implements OnCompletionListener {
599 public void onCompletion(MediaPlayer mediaPlayer) {
600 mediaPlayer.seekTo(0);