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.SpannableStringBuilder;
41 import android.text.ClipboardManager;
42 import android.text.style.UnderlineSpan;
43 import android.view.Gravity;
44 import android.view.KeyEvent;
45 import android.view.Menu;
46 import android.view.MenuItem;
47 import android.view.SurfaceHolder;
48 import android.view.SurfaceView;
49 import android.view.View;
50 import android.view.ViewGroup;
51 import android.view.Window;
52 import android.view.WindowManager;
53 import android.widget.Button;
54 import android.widget.ImageView;
55 import android.widget.TextView;
56 import com.google.zxing.Result;
57 import com.google.zxing.ResultPoint;
58 import com.google.zxing.client.android.result.ResultButtonListener;
59 import com.google.zxing.client.android.result.ResultHandler;
60 import com.google.zxing.client.android.result.ResultHandlerFactory;
62 import java.io.IOException;
65 * The barcode reader activity itself. This is loosely based on the CameraPreview
66 * example included in the Android SDK.
68 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
70 private static final int SHARE_ID = Menu.FIRST;
71 private static final int SETTINGS_ID = Menu.FIRST + 1;
72 private static final int HELP_ID = Menu.FIRST + 2;
73 private static final int ABOUT_ID = Menu.FIRST + 3;
75 private static final int MAX_RESULT_IMAGE_SIZE = 150;
76 private static final int INTENT_RESULT_DURATION = 1500;
77 private static final float BEEP_VOLUME = 0.15f;
78 private static final long VIBRATE_DURATION = 200;
80 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
82 public CaptureActivityHandler mHandler;
84 private ViewfinderView mViewfinderView;
85 private View mStatusView;
86 private View mResultView;
87 private MediaPlayer mMediaPlayer;
88 private Result mLastResult;
89 private boolean mHasSurface;
90 private boolean mPlayBeep;
91 private boolean mVibrate;
92 private boolean mCopyToClipboard;
93 private boolean mScanIntent;
94 private String mDecodeMode;
96 private final OnCompletionListener mBeepListener = new BeepListener();
99 public void onCreate(Bundle icicle) {
100 super.onCreate(icicle);
102 Window window = getWindow();
103 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
104 setContentView(R.layout.capture);
106 CameraManager.init(getApplication());
107 mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
108 mResultView = findViewById(R.id.result_view);
109 mStatusView = findViewById(R.id.status_view);
114 showHelpOnFirstLaunch();
118 protected void onResume() {
121 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
122 SurfaceHolder surfaceHolder = surfaceView.getHolder();
124 // The activity was paused but not stopped, so the surface still exists. Therefore
125 // surfaceCreated() won't be called, so init the camera here.
126 initCamera(surfaceHolder);
128 // Install the callback and wait for surfaceCreated() to init the camera.
129 surfaceHolder.addCallback(this);
130 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
133 Intent intent = getIntent();
134 String action = intent.getAction();
135 if (intent != null && action != null && (action.equals(Intents.Scan.ACTION) ||
136 action.equals(Intents.Scan.DEPRECATED_ACTION))) {
138 mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
143 if (mLastResult == null) {
148 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
149 mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
150 mVibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
151 mCopyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
156 protected void onPause() {
158 if (mHandler != null) {
159 mHandler.quitSynchronously();
162 CameraManager.get().closeDriver();
166 public boolean onKeyDown(int keyCode, KeyEvent event) {
167 if (keyCode == KeyEvent.KEYCODE_BACK) {
169 setResult(RESULT_CANCELED);
172 } else if (mLastResult != null) {
174 mHandler.sendEmptyMessage(R.id.restart_preview);
177 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
178 // Handle these events so they don't launch the Camera app
181 return super.onKeyDown(keyCode, event);
185 public boolean onCreateOptionsMenu(Menu menu) {
186 super.onCreateOptionsMenu(menu);
187 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
188 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
189 .setIcon(android.R.drawable.ic_menu_preferences);
190 menu.add(0, HELP_ID, 0, R.string.menu_help)
191 .setIcon(android.R.drawable.ic_menu_help);
192 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
193 .setIcon(android.R.drawable.ic_menu_info_details);
197 // Don't display the share menu item if the result overlay is showing.
199 public boolean onPrepareOptionsMenu(Menu menu) {
200 super.onPrepareOptionsMenu(menu);
201 menu.findItem(SHARE_ID).setVisible(mLastResult == null);
206 public boolean onOptionsItemSelected(MenuItem item) {
207 switch (item.getItemId()) {
209 Intent intent = new Intent(Intent.ACTION_VIEW);
210 intent.setClassName(this, ShareActivity.class.getName());
211 startActivity(intent);
215 Intent intent = new Intent(Intent.ACTION_VIEW);
216 intent.setClassName(this, PreferencesActivity.class.getName());
217 startActivity(intent);
221 Intent intent = new Intent(Intent.ACTION_VIEW);
222 intent.setClassName(this, HelpActivity.class.getName());
223 startActivity(intent);
227 AlertDialog.Builder builder = new AlertDialog.Builder(this);
228 builder.setTitle(R.string.title_about);
229 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
230 builder.setIcon(R.drawable.zxing_icon);
231 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
232 builder.setNegativeButton(R.string.button_cancel, null);
236 return super.onOptionsItemSelected(item);
240 public void onConfigurationChanged(Configuration config) {
241 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
242 super.onConfigurationChanged(config);
245 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
246 public void onClick(android.content.DialogInterface dialogInterface, int i) {
247 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
248 startActivity(intent);
252 public void surfaceCreated(SurfaceHolder holder) {
259 public void surfaceDestroyed(SurfaceHolder holder) {
263 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
268 * A valid barcode has been found, so give an indication of success and show the results.
270 * @param rawResult The contents of the barcode.
271 * @param barcode A greyscale bitmap of the camera data which was decoded.
272 * @param duration How long the decoding took in milliseconds.
274 public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
275 mLastResult = rawResult;
276 playBeepSoundAndVibrate();
277 drawResultPoints(barcode, rawResult);
280 handleDecodeForScanIntent(rawResult, barcode, duration);
282 mStatusView.setVisibility(View.GONE);
283 mViewfinderView.setVisibility(View.GONE);
284 mResultView.setVisibility(View.VISIBLE);
286 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
287 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
288 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
289 barcodeImageView.setImageBitmap(barcode);
291 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
292 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
293 rawResult.getBarcodeFormat().toString());
295 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
296 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
297 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
298 resultHandler.getType().toString());
300 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
301 CharSequence title = getString(resultHandler.getDisplayTitle());
302 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
303 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
304 CharSequence displayContents = resultHandler.getDisplayContents();
305 styled.append(displayContents);
306 contentsTextView.setText(styled);
308 int buttonCount = resultHandler.getButtonCount();
309 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
310 buttonView.requestFocus();
311 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
312 Button button = (Button) buttonView.getChildAt(x);
313 if (x < buttonCount) {
314 button.setVisibility(View.VISIBLE);
315 button.setText(resultHandler.getButtonText(x));
316 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
318 button.setVisibility(View.GONE);
322 if (mCopyToClipboard) {
323 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
324 clipboard.setText(displayContents);
330 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
332 * @param barcode A bitmap of the captured image.
333 * @param rawResult The decoded results which contains the points to draw.
335 private void drawResultPoints(Bitmap barcode, Result rawResult) {
336 ResultPoint[] points = rawResult.getResultPoints();
337 if (points != null && points.length > 0) {
338 Canvas canvas = new Canvas(barcode);
339 Paint paint = new Paint();
340 paint.setColor(getResources().getColor(R.color.result_image_border));
341 paint.setStrokeWidth(3);
342 paint.setStyle(Paint.Style.STROKE);
343 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
344 canvas.drawRect(border, paint);
346 paint.setColor(getResources().getColor(R.color.result_points));
347 if (points.length == 2) {
348 paint.setStrokeWidth(4);
349 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
350 points[1].getY(), paint);
352 paint.setStrokeWidth(10);
353 for (int x = 0; x < points.length; x++) {
354 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
360 private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
361 mViewfinderView.drawResultBitmap(barcode);
363 // Since this message will only be shown for a second, just tell the user what kind of
364 // barcode was found (e.g. contact info) rather than the full contents, which they won't
365 // have time to read.
366 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
367 TextView textView = (TextView) findViewById(R.id.status_text_view);
368 textView.setGravity(Gravity.CENTER);
369 textView.setTextSize(18.0f);
370 textView.setText(getString(resultHandler.getDisplayTitle()));
372 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
374 if (mCopyToClipboard) {
375 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
376 clipboard.setText(resultHandler.getDisplayContents());
379 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
380 // the deprecated intent is retired.
381 Intent intent = new Intent(getIntent().getAction());
382 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
383 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
384 Message message = Message.obtain(mHandler, R.id.return_scan_result);
385 message.obj = intent;
386 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
390 * We want the help screen to be shown automatically the first time a new version of the app is
391 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
392 * it to a value stored as a preference.
394 private void showHelpOnFirstLaunch() {
396 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
397 int currentVersion = info.versionCode;
398 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
399 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
400 if (currentVersion > lastVersion) {
401 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
402 Intent intent = new Intent(Intent.ACTION_VIEW);
403 intent.setClassName(this, HelpActivity.class.getName());
404 startActivity(intent);
406 } catch (PackageManager.NameNotFoundException e) {
412 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
415 private void initBeepSound() {
416 if (mPlayBeep && mMediaPlayer == null) {
417 mMediaPlayer = new MediaPlayer();
418 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
419 mMediaPlayer.setOnCompletionListener(mBeepListener);
421 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
423 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
426 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
427 mMediaPlayer.prepare();
428 } catch (IOException e) {
434 private void playBeepSoundAndVibrate() {
435 if (mPlayBeep && mMediaPlayer != null) {
436 mMediaPlayer.start();
439 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
440 vibrator.vibrate(VIBRATE_DURATION);
444 private void initCamera(SurfaceHolder surfaceHolder) {
445 CameraManager.get().openDriver(surfaceHolder);
446 if (mHandler == null) {
447 boolean beginScanning = mLastResult == null;
448 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
452 private void resetStatusView() {
453 mResultView.setVisibility(View.GONE);
454 mStatusView.setVisibility(View.VISIBLE);
455 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
456 mViewfinderView.setVisibility(View.VISIBLE);
458 TextView textView = (TextView) findViewById(R.id.status_text_view);
459 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
460 textView.setTextSize(14.0f);
461 textView.setText(R.string.msg_default_status);
465 public void drawViewfinder() {
466 mViewfinderView.drawViewfinder();
470 * When the beep has finished playing, rewind to queue up another one.
472 private static class BeepListener implements OnCompletionListener {
473 public void onCompletion(MediaPlayer mediaPlayer) {
474 mediaPlayer.seekTo(0);