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 android.graphics.drawable.BitmapDrawable;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
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.history.HistoryManager;
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.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.Message;
47 import android.os.Vibrator;
48 import android.os.Handler;
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.15f;
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 public Handler getHandler() {
133 public void onCreate(Bundle icicle) {
134 Log.i(TAG, "Creating CaptureActivity");
135 super.onCreate(icicle);
137 Window window = getWindow();
138 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
139 setContentView(R.layout.capture);
141 CameraManager.init(getApplication());
142 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
143 resultView = findViewById(R.id.result_view);
144 statusView = findViewById(R.id.status_view);
148 historyManager = new HistoryManager(this);
149 historyManager.trimHistory();
151 showHelpOnFirstLaunch();
155 protected void onResume() {
158 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
159 SurfaceHolder surfaceHolder = surfaceView.getHolder();
161 // The activity was paused but not stopped, so the surface still exists. Therefore
162 // surfaceCreated() won't be called, so init the camera here.
163 initCamera(surfaceHolder);
165 // Install the callback and wait for surfaceCreated() to init the camera.
166 surfaceHolder.addCallback(this);
167 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
170 Intent intent = getIntent();
171 String action = intent == null ? null : intent.getAction();
172 String dataString = intent == null ? null : intent.getDataString();
173 if (intent != null && action != null) {
174 if (action.equals(Intents.Scan.ACTION)) {
175 // Scan the formats the intent requested, and return the result to the calling activity.
176 source = Source.NATIVE_APP_INTENT;
177 decodeMode = intent.getStringExtra(Intents.Scan.MODE);
179 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
180 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
181 // Scan only products and send the result to mobile Product Search.
182 source = Source.PRODUCT_SEARCH_LINK;
183 sourceUrl = dataString;
184 decodeMode = Intents.Scan.PRODUCT_MODE;
186 } else if (dataString != null && dataString.equals(ZXING_URL)) {
187 // Scan all formats and handle the results ourselves.
188 // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
189 source = Source.ZXING_LINK;
190 sourceUrl = dataString;
194 // Scan all formats and handle the results ourselves (launched from Home).
195 source = Source.NONE;
200 source = Source.NONE;
202 if (lastResult == null) {
207 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
208 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
209 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
210 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
215 protected void onPause() {
217 if (handler != null) {
218 handler.quitSynchronously();
221 CameraManager.get().closeDriver();
225 public boolean onKeyDown(int keyCode, KeyEvent event) {
226 if (keyCode == KeyEvent.KEYCODE_BACK) {
227 if (source == Source.NATIVE_APP_INTENT) {
228 setResult(RESULT_CANCELED);
231 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
233 handler.sendEmptyMessage(R.id.restart_preview);
236 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
237 // Handle these events so they don't launch the Camera app
240 return super.onKeyDown(keyCode, event);
244 public boolean onCreateOptionsMenu(Menu menu) {
245 super.onCreateOptionsMenu(menu);
246 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
247 menu.add(0, HISTORY_ID, 0, R.string.menu_history).setIcon(android.R.drawable.ic_menu_recent_history);
248 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
249 .setIcon(android.R.drawable.ic_menu_preferences);
250 menu.add(0, HELP_ID, 0, R.string.menu_help)
251 .setIcon(android.R.drawable.ic_menu_help);
252 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
253 .setIcon(android.R.drawable.ic_menu_info_details);
257 // Don't display the share menu item if the result overlay is showing.
259 public boolean onPrepareOptionsMenu(Menu menu) {
260 super.onPrepareOptionsMenu(menu);
261 menu.findItem(SHARE_ID).setVisible(lastResult == null);
266 public boolean onOptionsItemSelected(MenuItem item) {
267 switch (item.getItemId()) {
269 Intent intent = new Intent(Intent.ACTION_VIEW);
270 intent.setClassName(this, ShareActivity.class.getName());
271 startActivity(intent);
275 AlertDialog historyAlert = historyManager.buildAlert();
280 Intent intent = new Intent(Intent.ACTION_VIEW);
281 intent.setClassName(this, PreferencesActivity.class.getName());
282 startActivity(intent);
286 Intent intent = new Intent(Intent.ACTION_VIEW);
287 intent.setClassName(this, HelpActivity.class.getName());
288 startActivity(intent);
292 AlertDialog.Builder builder = new AlertDialog.Builder(this);
293 builder.setTitle(getString(R.string.title_about) + versionName);
294 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
295 builder.setIcon(R.drawable.zxing_icon);
296 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
297 builder.setNegativeButton(R.string.button_cancel, null);
301 return super.onOptionsItemSelected(item);
305 public void onConfigurationChanged(Configuration config) {
306 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
307 super.onConfigurationChanged(config);
310 public void surfaceCreated(SurfaceHolder holder) {
317 public void surfaceDestroyed(SurfaceHolder holder) {
321 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
326 * A valid barcode has been found, so give an indication of success and show the results.
328 * @param rawResult The contents of the barcode.
329 * @param barcode A greyscale bitmap of the camera data which was decoded.
331 public void handleDecode(Result rawResult, Bitmap barcode) {
332 lastResult = rawResult;
333 historyManager.addHistoryItem(rawResult);
334 if (barcode == null) {
335 // This is from history -- no saved barcode
336 handleDecodeInternally(rawResult, null);
338 playBeepSoundAndVibrate();
339 drawResultPoints(barcode, rawResult);
341 case NATIVE_APP_INTENT:
342 case PRODUCT_SEARCH_LINK:
343 handleDecodeExternally(rawResult, barcode);
347 handleDecodeInternally(rawResult, barcode);
354 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
356 * @param barcode A bitmap of the captured image.
357 * @param rawResult The decoded results which contains the points to draw.
359 private void drawResultPoints(Bitmap barcode, Result rawResult) {
360 ResultPoint[] points = rawResult.getResultPoints();
361 if (points != null && points.length > 0) {
362 Canvas canvas = new Canvas(barcode);
363 Paint paint = new Paint();
364 paint.setColor(getResources().getColor(R.color.result_image_border));
365 paint.setStrokeWidth(3.0f);
366 paint.setStyle(Paint.Style.STROKE);
367 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
368 canvas.drawRect(border, paint);
370 paint.setColor(getResources().getColor(R.color.result_points));
371 if (points.length == 2) {
372 paint.setStrokeWidth(4.0f);
373 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
374 points[1].getY(), paint);
376 paint.setStrokeWidth(10.0f);
377 for (ResultPoint point : points) {
378 canvas.drawPoint(point.getX(), point.getY(), paint);
384 // Put up our own UI for how to handle the decoded contents.
385 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
386 statusView.setVisibility(View.GONE);
387 viewfinderView.setVisibility(View.GONE);
388 resultView.setVisibility(View.VISIBLE);
390 if (barcode == null) {
391 barcode = ((BitmapDrawable) getResources().getDrawable(R.drawable.unknown_barcode)).getBitmap();
393 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
394 barcodeImageView.setVisibility(View.VISIBLE);
395 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
396 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
397 barcodeImageView.setImageBitmap(barcode);
399 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
400 formatTextView.setVisibility(View.VISIBLE);
401 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
402 rawResult.getBarcodeFormat().toString());
404 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
405 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
406 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
407 resultHandler.getType().toString());
409 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
410 CharSequence title = getString(resultHandler.getDisplayTitle());
411 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
412 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
413 CharSequence displayContents = resultHandler.getDisplayContents();
414 styled.append(displayContents);
415 contentsTextView.setText(styled);
417 int buttonCount = resultHandler.getButtonCount();
418 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
419 buttonView.requestFocus();
420 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
421 TextView button = (TextView) buttonView.getChildAt(x);
422 if (x < buttonCount) {
423 button.setVisibility(View.VISIBLE);
424 button.setText(resultHandler.getButtonText(x));
425 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
427 button.setVisibility(View.GONE);
431 if (copyToClipboard) {
432 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
433 clipboard.setText(displayContents);
437 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
438 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
439 viewfinderView.drawResultBitmap(barcode);
441 // Since this message will only be shown for a second, just tell the user what kind of
442 // barcode was found (e.g. contact info) rather than the full contents, which they won't
443 // have time to read.
444 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
445 TextView textView = (TextView) findViewById(R.id.status_text_view);
446 textView.setGravity(Gravity.CENTER);
447 textView.setTextSize(18.0f);
448 textView.setText(getString(resultHandler.getDisplayTitle()));
450 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
452 if (copyToClipboard) {
453 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
454 clipboard.setText(resultHandler.getDisplayContents());
457 if (source == Source.NATIVE_APP_INTENT) {
458 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
459 // the deprecated intent is retired.
460 Intent intent = new Intent(getIntent().getAction());
461 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
462 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
463 Message message = Message.obtain(handler, R.id.return_scan_result);
464 message.obj = intent;
465 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
466 } else if (source == Source.PRODUCT_SEARCH_LINK) {
467 // Reformulate the URL which triggered us into a query, so that the request goes to the same
468 // TLD as the scan URL.
469 Message message = Message.obtain(handler, R.id.launch_product_query);
470 int end = sourceUrl.lastIndexOf("/scan");
471 message.obj = sourceUrl.substring(0, end) + "?q=" +
472 resultHandler.getDisplayContents().toString() + "&source=zxing";
473 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
478 * We want the help screen to be shown automatically the first time a new version of the app is
479 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
480 * it to a value stored as a preference.
482 private void showHelpOnFirstLaunch() {
484 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
485 int currentVersion = info.versionCode;
486 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
487 // version name here for display in the about box later.
488 this.versionName = info.versionName;
489 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
490 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
491 if (currentVersion > lastVersion) {
492 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
493 Intent intent = new Intent(Intent.ACTION_VIEW);
494 intent.setClassName(this, HelpActivity.class.getName());
495 startActivity(intent);
497 } catch (PackageManager.NameNotFoundException e) {
503 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
506 private void initBeepSound() {
507 if (playBeep && mediaPlayer == null) {
508 mediaPlayer = new MediaPlayer();
509 mediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
510 mediaPlayer.setOnCompletionListener(beepListener);
512 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
514 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
517 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
518 mediaPlayer.prepare();
519 } catch (IOException e) {
525 private void playBeepSoundAndVibrate() {
526 if (playBeep && mediaPlayer != null) {
530 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
531 vibrator.vibrate(VIBRATE_DURATION);
535 private void initCamera(SurfaceHolder surfaceHolder) {
537 CameraManager.get().openDriver(surfaceHolder);
538 } catch (IOException ioe) {
542 if (handler == null) {
543 boolean beginScanning = lastResult == null;
544 handler = new CaptureActivityHandler(this, decodeMode, beginScanning);
548 private void resetStatusView() {
549 resultView.setVisibility(View.GONE);
550 statusView.setVisibility(View.VISIBLE);
551 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
552 viewfinderView.setVisibility(View.VISIBLE);
554 TextView textView = (TextView) findViewById(R.id.status_text_view);
555 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
556 textView.setTextSize(14.0f);
557 textView.setText(R.string.msg_default_status);
561 public void drawViewfinder() {
562 viewfinderView.drawViewfinder();
566 * When the beep has finished playing, rewind to queue up another one.
568 private static class BeepListener implements OnCompletionListener {
569 public void onCompletion(MediaPlayer mediaPlayer) {
570 mediaPlayer.seekTo(0);