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.result.ResultButtonListener;
22 import com.google.zxing.client.android.result.ResultHandler;
23 import com.google.zxing.client.android.result.ResultHandlerFactory;
25 import android.app.Activity;
26 import android.app.AlertDialog;
27 import android.content.DialogInterface;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.pm.PackageInfo;
31 import android.content.pm.PackageManager;
32 import android.content.res.AssetFileDescriptor;
33 import android.content.res.Configuration;
34 import android.graphics.Bitmap;
35 import android.graphics.Canvas;
36 import android.graphics.Paint;
37 import android.graphics.Rect;
38 import android.media.AudioManager;
39 import android.media.MediaPlayer;
40 import android.media.MediaPlayer.OnCompletionListener;
41 import android.net.Uri;
42 import android.os.Bundle;
43 import android.os.Message;
44 import android.os.Vibrator;
45 import android.preference.PreferenceManager;
46 import android.text.ClipboardManager;
47 import android.text.SpannableStringBuilder;
48 import android.text.style.UnderlineSpan;
49 import android.util.Log;
50 import android.view.Gravity;
51 import android.view.KeyEvent;
52 import android.view.Menu;
53 import android.view.MenuItem;
54 import android.view.SurfaceHolder;
55 import android.view.SurfaceView;
56 import android.view.View;
57 import android.view.ViewGroup;
58 import android.view.Window;
59 import android.view.WindowManager;
60 import android.widget.Button;
61 import android.widget.ImageView;
62 import android.widget.TextView;
64 import java.io.IOException;
67 * The barcode reader activity itself. This is loosely based on the CameraPreview
68 * example included in the Android SDK.
70 * @author dswitkin@google.com (Daniel Switkin)
72 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
73 private static final String TAG = "CaptureActivity";
75 private static final int SHARE_ID = Menu.FIRST;
76 private static final int SETTINGS_ID = Menu.FIRST + 1;
77 private static final int HELP_ID = Menu.FIRST + 2;
78 private static final int ABOUT_ID = Menu.FIRST + 3;
80 private static final int MAX_RESULT_IMAGE_SIZE = 150;
81 private static final long INTENT_RESULT_DURATION = 1500L;
82 private static final float BEEP_VOLUME = 0.15f;
83 private static final long VIBRATE_DURATION = 200L;
85 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
86 private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
87 private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
88 private static final String ZXING_URL = "http://zxing.appspot.com/scan";
97 public CaptureActivityHandler handler;
99 private ViewfinderView viewfinderView;
100 private View statusView;
101 private View resultView;
102 private MediaPlayer mediaPlayer;
103 private Result lastResult;
104 private boolean hasSurface;
105 private boolean playBeep;
106 private boolean vibrate;
107 private boolean copyToClipboard;
108 private Source source;
109 private String sourceUrl;
110 private String decodeMode;
111 private String versionName;
113 private final OnCompletionListener beepListener = new BeepListener();
115 private final DialogInterface.OnClickListener aboutListener =
116 new DialogInterface.OnClickListener() {
117 public void onClick(DialogInterface dialogInterface, int i) {
118 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
119 startActivity(intent);
124 public void onCreate(Bundle icicle) {
125 Log.i(TAG, "Creating CaptureActivity");
126 super.onCreate(icicle);
128 Window window = getWindow();
129 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
130 setContentView(R.layout.capture);
132 CameraManager.init(getApplication());
133 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
134 resultView = findViewById(R.id.result_view);
135 statusView = findViewById(R.id.status_view);
140 showHelpOnFirstLaunch();
144 protected void onResume() {
147 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
148 SurfaceHolder surfaceHolder = surfaceView.getHolder();
150 // The activity was paused but not stopped, so the surface still exists. Therefore
151 // surfaceCreated() won't be called, so init the camera here.
152 initCamera(surfaceHolder);
154 // Install the callback and wait for surfaceCreated() to init the camera.
155 surfaceHolder.addCallback(this);
156 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
159 Intent intent = getIntent();
160 String action = intent == null ? null : intent.getAction();
161 String dataString = intent == null ? null : intent.getDataString();
162 if (intent != null && action != null) {
163 if (action.equals(Intents.Scan.ACTION)) {
164 // Scan the formats the intent requested, and return the result to the calling activity.
165 source = Source.NATIVE_APP_INTENT;
166 decodeMode = intent.getStringExtra(Intents.Scan.MODE);
168 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
169 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
170 // Scan only products and send the result to mobile Product Search.
171 source = Source.PRODUCT_SEARCH_LINK;
172 sourceUrl = dataString;
173 decodeMode = Intents.Scan.PRODUCT_MODE;
175 } else if (dataString != null && dataString.equals(ZXING_URL)) {
176 // Scan all formats and handle the results ourselves.
177 // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
178 source = Source.ZXING_LINK;
179 sourceUrl = dataString;
183 // Scan all formats and handle the results ourselves (launched from Home).
184 source = Source.NONE;
189 source = Source.NONE;
191 if (lastResult == null) {
196 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
197 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
198 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
199 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
204 protected void onPause() {
206 if (handler != null) {
207 handler.quitSynchronously();
210 CameraManager.get().closeDriver();
214 public boolean onKeyDown(int keyCode, KeyEvent event) {
215 if (keyCode == KeyEvent.KEYCODE_BACK) {
216 if (source == Source.NATIVE_APP_INTENT) {
217 setResult(RESULT_CANCELED);
220 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
222 handler.sendEmptyMessage(R.id.restart_preview);
225 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
226 // Handle these events so they don't launch the Camera app
229 return super.onKeyDown(keyCode, event);
233 public boolean onCreateOptionsMenu(Menu menu) {
234 super.onCreateOptionsMenu(menu);
235 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
236 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
237 .setIcon(android.R.drawable.ic_menu_preferences);
238 menu.add(0, HELP_ID, 0, R.string.menu_help)
239 .setIcon(android.R.drawable.ic_menu_help);
240 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
241 .setIcon(android.R.drawable.ic_menu_info_details);
245 // Don't display the share menu item if the result overlay is showing.
247 public boolean onPrepareOptionsMenu(Menu menu) {
248 super.onPrepareOptionsMenu(menu);
249 menu.findItem(SHARE_ID).setVisible(lastResult == null);
254 public boolean onOptionsItemSelected(MenuItem item) {
255 switch (item.getItemId()) {
257 Intent intent = new Intent(Intent.ACTION_VIEW);
258 intent.setClassName(this, ShareActivity.class.getName());
259 startActivity(intent);
263 Intent intent = new Intent(Intent.ACTION_VIEW);
264 intent.setClassName(this, PreferencesActivity.class.getName());
265 startActivity(intent);
269 Intent intent = new Intent(Intent.ACTION_VIEW);
270 intent.setClassName(this, HelpActivity.class.getName());
271 startActivity(intent);
275 AlertDialog.Builder builder = new AlertDialog.Builder(this);
276 builder.setTitle(getString(R.string.title_about) + versionName);
277 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
278 builder.setIcon(R.drawable.zxing_icon);
279 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
280 builder.setNegativeButton(R.string.button_cancel, null);
284 return super.onOptionsItemSelected(item);
288 public void onConfigurationChanged(Configuration config) {
289 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
290 super.onConfigurationChanged(config);
293 public void surfaceCreated(SurfaceHolder holder) {
300 public void surfaceDestroyed(SurfaceHolder holder) {
304 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
309 * A valid barcode has been found, so give an indication of success and show the results.
311 * @param rawResult The contents of the barcode.
312 * @param barcode A greyscale bitmap of the camera data which was decoded.
314 public void handleDecode(Result rawResult, Bitmap barcode) {
315 lastResult = rawResult;
316 playBeepSoundAndVibrate();
317 drawResultPoints(barcode, rawResult);
320 case NATIVE_APP_INTENT:
321 case PRODUCT_SEARCH_LINK:
322 handleDecodeExternally(rawResult, barcode);
326 handleDecodeInternally(rawResult, barcode);
332 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
334 * @param barcode A bitmap of the captured image.
335 * @param rawResult The decoded results which contains the points to draw.
337 private void drawResultPoints(Bitmap barcode, Result rawResult) {
338 ResultPoint[] points = rawResult.getResultPoints();
339 if (points != null && points.length > 0) {
340 Canvas canvas = new Canvas(barcode);
341 Paint paint = new Paint();
342 paint.setColor(getResources().getColor(R.color.result_image_border));
343 paint.setStrokeWidth(3.0f);
344 paint.setStyle(Paint.Style.STROKE);
345 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
346 canvas.drawRect(border, paint);
348 paint.setColor(getResources().getColor(R.color.result_points));
349 if (points.length == 2) {
350 paint.setStrokeWidth(4.0f);
351 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
352 points[1].getY(), paint);
354 paint.setStrokeWidth(10.0f);
355 for (ResultPoint point : points) {
356 canvas.drawPoint(point.getX(), point.getY(), paint);
362 // Put up our own UI for how to handle the decoded contents.
363 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
364 statusView.setVisibility(View.GONE);
365 viewfinderView.setVisibility(View.GONE);
366 resultView.setVisibility(View.VISIBLE);
368 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
369 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
370 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
371 barcodeImageView.setImageBitmap(barcode);
373 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
374 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
375 rawResult.getBarcodeFormat().toString());
377 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
378 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
379 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
380 resultHandler.getType().toString());
382 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
383 CharSequence title = getString(resultHandler.getDisplayTitle());
384 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
385 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
386 CharSequence displayContents = resultHandler.getDisplayContents();
387 styled.append(displayContents);
388 contentsTextView.setText(styled);
390 int buttonCount = resultHandler.getButtonCount();
391 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
392 buttonView.requestFocus();
393 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
394 Button button = (Button) buttonView.getChildAt(x);
395 if (x < buttonCount) {
396 button.setVisibility(View.VISIBLE);
397 button.setText(resultHandler.getButtonText(x));
398 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
400 button.setVisibility(View.GONE);
404 if (copyToClipboard) {
405 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
406 clipboard.setText(displayContents);
410 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
411 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
412 viewfinderView.drawResultBitmap(barcode);
414 // Since this message will only be shown for a second, just tell the user what kind of
415 // barcode was found (e.g. contact info) rather than the full contents, which they won't
416 // have time to read.
417 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
418 TextView textView = (TextView) findViewById(R.id.status_text_view);
419 textView.setGravity(Gravity.CENTER);
420 textView.setTextSize(18.0f);
421 textView.setText(getString(resultHandler.getDisplayTitle()));
423 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
425 if (copyToClipboard) {
426 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
427 clipboard.setText(resultHandler.getDisplayContents());
430 if (source == Source.NATIVE_APP_INTENT) {
431 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
432 // the deprecated intent is retired.
433 Intent intent = new Intent(getIntent().getAction());
434 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
435 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
436 Message message = Message.obtain(handler, R.id.return_scan_result);
437 message.obj = intent;
438 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
439 } else if (source == Source.PRODUCT_SEARCH_LINK) {
440 // Reformulate the URL which triggered us into a query, so that the request goes to the same
441 // TLD as the scan URL.
442 Message message = Message.obtain(handler, R.id.launch_product_query);
443 int end = sourceUrl.lastIndexOf("/scan");
444 message.obj = sourceUrl.substring(0, end) + "?q=" +
445 resultHandler.getDisplayContents().toString() + "&source=zxing";
446 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
451 * We want the help screen to be shown automatically the first time a new version of the app is
452 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
453 * it to a value stored as a preference.
455 private void showHelpOnFirstLaunch() {
457 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
458 int currentVersion = info.versionCode;
459 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
460 // version name here for display in the about box later.
461 this.versionName = info.versionName;
462 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
463 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
464 if (currentVersion > lastVersion) {
465 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
466 Intent intent = new Intent(Intent.ACTION_VIEW);
467 intent.setClassName(this, HelpActivity.class.getName());
468 startActivity(intent);
470 } catch (PackageManager.NameNotFoundException e) {
476 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
479 private void initBeepSound() {
480 if (playBeep && mediaPlayer == null) {
481 mediaPlayer = new MediaPlayer();
482 mediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
483 mediaPlayer.setOnCompletionListener(beepListener);
485 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
487 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
490 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
491 mediaPlayer.prepare();
492 } catch (IOException e) {
498 private void playBeepSoundAndVibrate() {
499 if (playBeep && mediaPlayer != null) {
503 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
504 vibrator.vibrate(VIBRATE_DURATION);
508 private void initCamera(SurfaceHolder surfaceHolder) {
510 CameraManager.get().openDriver(surfaceHolder);
511 } catch (IOException ioe) {
515 if (handler == null) {
516 boolean beginScanning = lastResult == null;
517 handler = new CaptureActivityHandler(this, decodeMode, beginScanning);
521 private void resetStatusView() {
522 resultView.setVisibility(View.GONE);
523 statusView.setVisibility(View.VISIBLE);
524 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
525 viewfinderView.setVisibility(View.VISIBLE);
527 TextView textView = (TextView) findViewById(R.id.status_text_view);
528 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
529 textView.setTextSize(14.0f);
530 textView.setText(R.string.msg_default_status);
534 public void drawViewfinder() {
535 viewfinderView.drawViewfinder();
539 * When the beep has finished playing, rewind to queue up another one.
541 private static class BeepListener implements OnCompletionListener {
542 public void onCompletion(MediaPlayer mediaPlayer) {
543 mediaPlayer.seekTo(0);