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.Context;
22 import android.content.DialogInterface;
23 import android.content.Intent;
24 import android.content.SharedPreferences;
25 import android.content.pm.PackageInfo;
26 import android.content.pm.PackageManager;
27 import android.content.res.AssetFileDescriptor;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.Canvas;
31 import android.graphics.Paint;
32 import android.graphics.Rect;
33 import android.media.AudioManager;
34 import android.media.MediaPlayer;
35 import android.media.MediaPlayer.OnCompletionListener;
36 import android.net.Uri;
37 import android.os.Bundle;
38 import android.os.Message;
39 import android.os.Vibrator;
40 import android.preference.PreferenceManager;
41 import android.text.SpannableStringBuilder;
42 import android.text.ClipboardManager;
43 import android.text.style.UnderlineSpan;
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 int SHARE_ID = Menu.FIRST;
72 private static final int SETTINGS_ID = Menu.FIRST + 1;
73 private static final int HELP_ID = Menu.FIRST + 2;
74 private static final int ABOUT_ID = Menu.FIRST + 3;
76 private static final int MAX_RESULT_IMAGE_SIZE = 150;
77 private static final int INTENT_RESULT_DURATION = 1500;
78 private static final float BEEP_VOLUME = 0.15f;
79 private static final long VIBRATE_DURATION = 200;
81 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
83 public CaptureActivityHandler mHandler;
85 private ViewfinderView mViewfinderView;
86 private View mStatusView;
87 private View mResultView;
88 private MediaPlayer mMediaPlayer;
89 private Result mLastResult;
90 private boolean mHasSurface;
91 private boolean mPlayBeep;
92 private boolean mVibrate;
93 private boolean mCopyToClipboard;
94 private boolean mScanIntent;
95 private String mDecodeMode;
97 private final OnCompletionListener mBeepListener = new BeepListener();
100 public void onCreate(Bundle icicle) {
101 super.onCreate(icicle);
103 Window window = getWindow();
104 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
105 setContentView(R.layout.capture);
107 CameraManager.init(getApplication());
108 mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
109 mResultView = findViewById(R.id.result_view);
110 mStatusView = findViewById(R.id.status_view);
115 showHelpOnFirstLaunch();
119 protected void onResume() {
122 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
123 SurfaceHolder surfaceHolder = surfaceView.getHolder();
125 // The activity was paused but not stopped, so the surface still exists. Therefore
126 // surfaceCreated() won't be called, so init the camera here.
127 initCamera(surfaceHolder);
129 // Install the callback and wait for surfaceCreated() to init the camera.
130 surfaceHolder.addCallback(this);
131 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
134 Intent intent = getIntent();
135 String action = intent.getAction();
136 if (intent != null && action != null && (action.equals(Intents.Scan.ACTION) ||
137 action.equals(Intents.Scan.DEPRECATED_ACTION))) {
139 mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
144 if (mLastResult == null) {
149 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
150 mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
151 mVibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
152 mCopyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
157 protected void onPause() {
159 if (mHandler != null) {
160 mHandler.quitSynchronously();
163 CameraManager.get().closeDriver();
167 public boolean onKeyDown(int keyCode, KeyEvent event) {
168 if (keyCode == KeyEvent.KEYCODE_BACK) {
170 setResult(RESULT_CANCELED);
173 } else if (mLastResult != null) {
175 mHandler.sendEmptyMessage(R.id.restart_preview);
178 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
179 // Handle these events so they don't launch the Camera app
182 return super.onKeyDown(keyCode, event);
186 public boolean onCreateOptionsMenu(Menu menu) {
187 super.onCreateOptionsMenu(menu);
188 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
189 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
190 .setIcon(android.R.drawable.ic_menu_preferences);
191 menu.add(0, HELP_ID, 0, R.string.menu_help)
192 .setIcon(android.R.drawable.ic_menu_help);
193 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
194 .setIcon(android.R.drawable.ic_menu_info_details);
198 // Don't display the share menu item if the result overlay is showing.
200 public boolean onPrepareOptionsMenu(Menu menu) {
201 super.onPrepareOptionsMenu(menu);
202 menu.findItem(SHARE_ID).setVisible(mLastResult == null);
207 public boolean onOptionsItemSelected(MenuItem item) {
208 switch (item.getItemId()) {
210 Intent intent = new Intent(Intent.ACTION_VIEW);
211 intent.setClassName(this, ShareActivity.class.getName());
212 startActivity(intent);
216 Intent intent = new Intent(Intent.ACTION_VIEW);
217 intent.setClassName(this, PreferencesActivity.class.getName());
218 startActivity(intent);
222 Intent intent = new Intent(Intent.ACTION_VIEW);
223 intent.setClassName(this, HelpActivity.class.getName());
224 startActivity(intent);
228 AlertDialog.Builder builder = new AlertDialog.Builder(this);
229 builder.setTitle(R.string.title_about);
230 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
231 builder.setIcon(R.drawable.zxing_icon);
232 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
233 builder.setNegativeButton(R.string.button_cancel, null);
237 return super.onOptionsItemSelected(item);
241 public void onConfigurationChanged(Configuration config) {
242 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
243 super.onConfigurationChanged(config);
246 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
247 public void onClick(android.content.DialogInterface dialogInterface, int i) {
248 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
249 startActivity(intent);
253 public void surfaceCreated(SurfaceHolder holder) {
260 public void surfaceDestroyed(SurfaceHolder holder) {
264 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
269 * A valid barcode has been found, so give an indication of success and show the results.
271 * @param rawResult The contents of the barcode.
272 * @param barcode A greyscale bitmap of the camera data which was decoded.
273 * @param duration How long the decoding took in milliseconds.
275 public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
276 mLastResult = rawResult;
277 playBeepSoundAndVibrate();
278 drawResultPoints(barcode, rawResult);
281 handleDecodeForScanIntent(rawResult, barcode, duration);
283 mStatusView.setVisibility(View.GONE);
284 mViewfinderView.setVisibility(View.GONE);
285 mResultView.setVisibility(View.VISIBLE);
287 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
288 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
289 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
290 barcodeImageView.setImageBitmap(barcode);
292 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
293 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
294 rawResult.getBarcodeFormat().toString());
296 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
297 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
298 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
299 resultHandler.getType().toString());
301 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
302 CharSequence title = getString(resultHandler.getDisplayTitle());
303 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
304 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
305 CharSequence displayContents = resultHandler.getDisplayContents();
306 styled.append(displayContents);
307 contentsTextView.setText(styled);
309 int buttonCount = resultHandler.getButtonCount();
310 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
311 buttonView.requestFocus();
312 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
313 Button button = (Button) buttonView.getChildAt(x);
314 if (x < buttonCount) {
315 button.setVisibility(View.VISIBLE);
316 button.setText(resultHandler.getButtonText(x));
317 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
319 button.setVisibility(View.GONE);
323 if (mCopyToClipboard) {
324 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
325 clipboard.setText(displayContents);
331 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
333 * @param barcode A bitmap of the captured image.
334 * @param rawResult The decoded results which contains the points to draw.
336 private void drawResultPoints(Bitmap barcode, Result rawResult) {
337 ResultPoint[] points = rawResult.getResultPoints();
338 if (points != null && points.length > 0) {
339 Canvas canvas = new Canvas(barcode);
340 Paint paint = new Paint();
341 paint.setColor(getResources().getColor(R.color.result_image_border));
342 paint.setStrokeWidth(3);
343 paint.setStyle(Paint.Style.STROKE);
344 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
345 canvas.drawRect(border, paint);
347 paint.setColor(getResources().getColor(R.color.result_points));
348 if (points.length == 2) {
349 paint.setStrokeWidth(4);
350 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
351 points[1].getY(), paint);
353 paint.setStrokeWidth(10);
354 for (int x = 0; x < points.length; x++) {
355 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
361 private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
362 mViewfinderView.drawResultBitmap(barcode);
364 // Since this message will only be shown for a second, just tell the user what kind of
365 // barcode was found (e.g. contact info) rather than the full contents, which they won't
366 // have time to read.
367 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
368 TextView textView = (TextView) findViewById(R.id.status_text_view);
369 textView.setGravity(Gravity.CENTER);
370 textView.setTextSize(18.0f);
371 textView.setText(getString(resultHandler.getDisplayTitle()));
373 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
375 if (mCopyToClipboard) {
376 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
377 clipboard.setText(resultHandler.getDisplayContents());
380 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
381 // the deprecated intent is retired.
382 Intent intent = new Intent(getIntent().getAction());
383 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
384 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
385 Message message = Message.obtain(mHandler, R.id.return_scan_result);
386 message.obj = intent;
387 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
391 * We want the help screen to be shown automatically the first time a new version of the app is
392 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
393 * it to a value stored as a preference.
395 private void showHelpOnFirstLaunch() {
397 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
398 int currentVersion = info.versionCode;
399 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
400 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
401 if (currentVersion > lastVersion) {
402 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
403 Intent intent = new Intent(Intent.ACTION_VIEW);
404 intent.setClassName(this, HelpActivity.class.getName());
405 startActivity(intent);
407 } catch (PackageManager.NameNotFoundException e) {
413 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
416 private void initBeepSound() {
417 if (mPlayBeep && mMediaPlayer == null) {
418 mMediaPlayer = new MediaPlayer();
419 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
420 mMediaPlayer.setOnCompletionListener(mBeepListener);
422 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
424 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
427 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
428 mMediaPlayer.prepare();
429 } catch (IOException e) {
435 private void playBeepSoundAndVibrate() {
436 if (mPlayBeep && mMediaPlayer != null) {
437 mMediaPlayer.start();
440 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
441 vibrator.vibrate(VIBRATE_DURATION);
445 private void initCamera(SurfaceHolder surfaceHolder) {
446 CameraManager.get().openDriver(surfaceHolder);
447 if (mHandler == null) {
448 boolean beginScanning = mLastResult == null;
449 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
453 private void resetStatusView() {
454 mResultView.setVisibility(View.GONE);
455 mStatusView.setVisibility(View.VISIBLE);
456 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
457 mViewfinderView.setVisibility(View.VISIBLE);
459 TextView textView = (TextView) findViewById(R.id.status_text_view);
460 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
461 textView.setTextSize(14.0f);
462 textView.setText(R.string.msg_default_status);
466 public void drawViewfinder() {
467 mViewfinderView.drawViewfinder();
471 * When the beep has finished playing, rewind to queue up another one.
473 private static class BeepListener implements OnCompletionListener {
474 public void onCompletion(MediaPlayer mediaPlayer) {
475 mediaPlayer.seekTo(0);