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.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.os.Vibrator;
39 import android.preference.PreferenceManager;
40 import android.text.ClipboardManager;
41 import android.text.SpannableStringBuilder;
42 import android.text.style.UnderlineSpan;
43 import android.util.Log;
44 import android.view.Gravity;
45 import android.view.KeyEvent;
46 import android.view.Menu;
47 import android.view.MenuItem;
48 import android.view.SurfaceHolder;
49 import android.view.SurfaceView;
50 import android.view.View;
51 import android.view.ViewGroup;
52 import android.view.Window;
53 import android.view.WindowManager;
54 import android.widget.Button;
55 import android.widget.ImageView;
56 import android.widget.TextView;
57 import com.google.zxing.Result;
58 import com.google.zxing.ResultPoint;
59 import com.google.zxing.client.android.result.ResultButtonListener;
60 import com.google.zxing.client.android.result.ResultHandler;
61 import com.google.zxing.client.android.result.ResultHandlerFactory;
63 import java.io.IOException;
66 * The barcode reader activity itself. This is loosely based on the CameraPreview
67 * example included in the Android SDK.
69 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
71 private static final String TAG = "CaptureActivity";
73 private static final int SHARE_ID = Menu.FIRST;
74 private static final int SETTINGS_ID = Menu.FIRST + 1;
75 private static final int HELP_ID = Menu.FIRST + 2;
76 private static final int ABOUT_ID = Menu.FIRST + 3;
78 private static final int MAX_RESULT_IMAGE_SIZE = 150;
79 private static final int INTENT_RESULT_DURATION = 1500;
80 private static final float BEEP_VOLUME = 0.15f;
81 private static final long VIBRATE_DURATION = 200;
83 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
84 private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
85 private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
86 private static final String ZXING_URL = "http://zxing.appspot.com/scan";
95 public CaptureActivityHandler mHandler;
97 private ViewfinderView mViewfinderView;
98 private View mStatusView;
99 private View mResultView;
100 private MediaPlayer mMediaPlayer;
101 private Result mLastResult;
102 private boolean mHasSurface;
103 private boolean mPlayBeep;
104 private boolean mVibrate;
105 private boolean mCopyToClipboard;
106 private Source mSource;
107 private String mSourceUrl;
108 private String mDecodeMode;
109 private String mVersionName;
111 private final OnCompletionListener mBeepListener = new BeepListener();
114 public void onCreate(Bundle icicle) {
115 Log.i(TAG, "Creating CaptureActivity");
116 super.onCreate(icicle);
118 Window window = getWindow();
119 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
120 setContentView(R.layout.capture);
122 CameraManager.init(getApplication());
123 mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
124 mResultView = findViewById(R.id.result_view);
125 mStatusView = findViewById(R.id.status_view);
130 showHelpOnFirstLaunch();
134 protected void onResume() {
137 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
138 SurfaceHolder surfaceHolder = surfaceView.getHolder();
140 // The activity was paused but not stopped, so the surface still exists. Therefore
141 // surfaceCreated() won't be called, so init the camera here.
142 initCamera(surfaceHolder);
144 // Install the callback and wait for surfaceCreated() to init the camera.
145 surfaceHolder.addCallback(this);
146 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
149 Intent intent = getIntent();
150 String action = intent.getAction();
151 String dataString = intent.getDataString();
152 if (intent != null && action != null) {
153 if (action.equals(Intents.Scan.ACTION) || action.equals(Intents.Scan.DEPRECATED_ACTION)) {
154 // Scan the formats the intent requested, and return the result to the calling activity.
155 mSource = Source.NATIVE_APP_INTENT;
156 mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
158 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
159 dataString.contains(PRODUCT_SEARCH_URL_PREFIX)) {
160 // Scan only products and send the result to mobile Product Search.
161 mSource = Source.PRODUCT_SEARCH_LINK;
162 mSourceUrl = dataString;
163 mDecodeMode = Intents.Scan.PRODUCT_MODE;
165 } else if (dataString != null && dataString.equals(ZXING_URL)) {
166 // Scan all formats and handle the results ourselves.
167 // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
168 mSource = Source.ZXING_LINK;
169 mSourceUrl = dataString;
173 // Scan all formats and handle the results ourselves (launched from Home).
174 mSource = Source.NONE;
179 mSource = Source.NONE;
181 if (mLastResult == null) {
186 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
187 mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
188 mVibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
189 mCopyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
194 protected void onPause() {
196 if (mHandler != null) {
197 mHandler.quitSynchronously();
200 CameraManager.get().closeDriver();
204 public boolean onKeyDown(int keyCode, KeyEvent event) {
205 if (keyCode == KeyEvent.KEYCODE_BACK) {
206 if (mSource == Source.NATIVE_APP_INTENT) {
207 setResult(RESULT_CANCELED);
210 } else if ((mSource == Source.NONE || mSource == Source.ZXING_LINK) && mLastResult != null) {
212 mHandler.sendEmptyMessage(R.id.restart_preview);
215 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
216 // Handle these events so they don't launch the Camera app
219 return super.onKeyDown(keyCode, event);
223 public boolean onCreateOptionsMenu(Menu menu) {
224 super.onCreateOptionsMenu(menu);
225 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
226 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
227 .setIcon(android.R.drawable.ic_menu_preferences);
228 menu.add(0, HELP_ID, 0, R.string.menu_help)
229 .setIcon(android.R.drawable.ic_menu_help);
230 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
231 .setIcon(android.R.drawable.ic_menu_info_details);
235 // Don't display the share menu item if the result overlay is showing.
237 public boolean onPrepareOptionsMenu(Menu menu) {
238 super.onPrepareOptionsMenu(menu);
239 menu.findItem(SHARE_ID).setVisible(mLastResult == null);
244 public boolean onOptionsItemSelected(MenuItem item) {
245 switch (item.getItemId()) {
247 Intent intent = new Intent(Intent.ACTION_VIEW);
248 intent.setClassName(this, ShareActivity.class.getName());
249 startActivity(intent);
253 Intent intent = new Intent(Intent.ACTION_VIEW);
254 intent.setClassName(this, PreferencesActivity.class.getName());
255 startActivity(intent);
259 Intent intent = new Intent(Intent.ACTION_VIEW);
260 intent.setClassName(this, HelpActivity.class.getName());
261 startActivity(intent);
265 AlertDialog.Builder builder = new AlertDialog.Builder(this);
266 builder.setTitle(getString(R.string.title_about) + mVersionName);
267 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
268 builder.setIcon(R.drawable.zxing_icon);
269 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
270 builder.setNegativeButton(R.string.button_cancel, null);
274 return super.onOptionsItemSelected(item);
278 public void onConfigurationChanged(Configuration config) {
279 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
280 super.onConfigurationChanged(config);
283 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
284 public void onClick(android.content.DialogInterface dialogInterface, int i) {
285 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
286 startActivity(intent);
290 public void surfaceCreated(SurfaceHolder holder) {
297 public void surfaceDestroyed(SurfaceHolder holder) {
301 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
306 * A valid barcode has been found, so give an indication of success and show the results.
308 * @param rawResult The contents of the barcode.
309 * @param barcode A greyscale bitmap of the camera data which was decoded.
311 public void handleDecode(Result rawResult, Bitmap barcode) {
312 mLastResult = rawResult;
313 playBeepSoundAndVibrate();
314 drawResultPoints(barcode, rawResult);
317 case NATIVE_APP_INTENT:
318 case PRODUCT_SEARCH_LINK:
319 handleDecodeExternally(rawResult, barcode);
323 handleDecodeInternally(rawResult, barcode);
329 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
331 * @param barcode A bitmap of the captured image.
332 * @param rawResult The decoded results which contains the points to draw.
334 private void drawResultPoints(Bitmap barcode, Result rawResult) {
335 ResultPoint[] points = rawResult.getResultPoints();
336 if (points != null && points.length > 0) {
337 Canvas canvas = new Canvas(barcode);
338 Paint paint = new Paint();
339 paint.setColor(getResources().getColor(R.color.result_image_border));
340 paint.setStrokeWidth(3);
341 paint.setStyle(Paint.Style.STROKE);
342 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
343 canvas.drawRect(border, paint);
345 paint.setColor(getResources().getColor(R.color.result_points));
346 if (points.length == 2) {
347 paint.setStrokeWidth(4);
348 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
349 points[1].getY(), paint);
351 paint.setStrokeWidth(10);
352 for (int x = 0; x < points.length; x++) {
353 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
359 // Put up our own UI for how to handle the decoded contents.
360 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
361 mStatusView.setVisibility(View.GONE);
362 mViewfinderView.setVisibility(View.GONE);
363 mResultView.setVisibility(View.VISIBLE);
365 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
366 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
367 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
368 barcodeImageView.setImageBitmap(barcode);
370 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
371 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
372 rawResult.getBarcodeFormat().toString());
374 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
375 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
376 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
377 resultHandler.getType().toString());
379 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
380 CharSequence title = getString(resultHandler.getDisplayTitle());
381 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
382 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
383 CharSequence displayContents = resultHandler.getDisplayContents();
384 styled.append(displayContents);
385 contentsTextView.setText(styled);
387 int buttonCount = resultHandler.getButtonCount();
388 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
389 buttonView.requestFocus();
390 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
391 Button button = (Button) buttonView.getChildAt(x);
392 if (x < buttonCount) {
393 button.setVisibility(View.VISIBLE);
394 button.setText(resultHandler.getButtonText(x));
395 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
397 button.setVisibility(View.GONE);
401 if (mCopyToClipboard) {
402 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
403 clipboard.setText(displayContents);
407 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
408 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
409 mViewfinderView.drawResultBitmap(barcode);
411 // Since this message will only be shown for a second, just tell the user what kind of
412 // barcode was found (e.g. contact info) rather than the full contents, which they won't
413 // have time to read.
414 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
415 TextView textView = (TextView) findViewById(R.id.status_text_view);
416 textView.setGravity(Gravity.CENTER);
417 textView.setTextSize(18.0f);
418 textView.setText(getString(resultHandler.getDisplayTitle()));
420 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
422 if (mCopyToClipboard) {
423 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
424 clipboard.setText(resultHandler.getDisplayContents());
427 if (mSource == Source.NATIVE_APP_INTENT) {
428 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
429 // the deprecated intent is retired.
430 Intent intent = new Intent(getIntent().getAction());
431 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
432 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
433 Message message = Message.obtain(mHandler, R.id.return_scan_result);
434 message.obj = intent;
435 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
436 } else if (mSource == Source.PRODUCT_SEARCH_LINK) {
437 // Reformulate the URL which triggered us into a query, so that the request goes to the same
438 // TLD as the scan URL.
439 Message message = Message.obtain(mHandler, R.id.launch_product_query);
440 int end = mSourceUrl.lastIndexOf("/scan");
441 message.obj = mSourceUrl.substring(0, end) + "?q=" +
442 resultHandler.getDisplayContents().toString() + "&source=zxing";
443 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
448 * We want the help screen to be shown automatically the first time a new version of the app is
449 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
450 * it to a value stored as a preference.
452 private void showHelpOnFirstLaunch() {
454 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
455 int currentVersion = info.versionCode;
456 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
457 // version name here for display in the about box later.
458 this.mVersionName = info.versionName;
459 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
460 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
461 if (currentVersion > lastVersion) {
462 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
463 Intent intent = new Intent(Intent.ACTION_VIEW);
464 intent.setClassName(this, HelpActivity.class.getName());
465 startActivity(intent);
467 } catch (PackageManager.NameNotFoundException e) {
473 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
476 private void initBeepSound() {
477 if (mPlayBeep && mMediaPlayer == null) {
478 mMediaPlayer = new MediaPlayer();
479 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
480 mMediaPlayer.setOnCompletionListener(mBeepListener);
482 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
484 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
487 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
488 mMediaPlayer.prepare();
489 } catch (IOException e) {
495 private void playBeepSoundAndVibrate() {
496 if (mPlayBeep && mMediaPlayer != null) {
497 mMediaPlayer.start();
500 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
501 vibrator.vibrate(VIBRATE_DURATION);
505 private void initCamera(SurfaceHolder surfaceHolder) {
506 CameraManager.get().openDriver(surfaceHolder);
507 if (mHandler == null) {
508 boolean beginScanning = mLastResult == null;
509 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
513 private void resetStatusView() {
514 mResultView.setVisibility(View.GONE);
515 mStatusView.setVisibility(View.VISIBLE);
516 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
517 mViewfinderView.setVisibility(View.VISIBLE);
519 TextView textView = (TextView) findViewById(R.id.status_text_view);
520 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
521 textView.setTextSize(14.0f);
522 textView.setText(R.string.msg_default_status);
526 public void drawViewfinder() {
527 mViewfinderView.drawViewfinder();
531 * When the beep has finished playing, rewind to queue up another one.
533 private static class BeepListener implements OnCompletionListener {
534 public void onCompletion(MediaPlayer mediaPlayer) {
535 mediaPlayer.seekTo(0);