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 android.util.Log;
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";
85 public CaptureActivityHandler mHandler;
87 private ViewfinderView mViewfinderView;
88 private View mStatusView;
89 private View mResultView;
90 private MediaPlayer mMediaPlayer;
91 private Result mLastResult;
92 private boolean mHasSurface;
93 private boolean mPlayBeep;
94 private boolean mVibrate;
95 private boolean mCopyToClipboard;
96 private boolean mScanIntent;
97 private String mDecodeMode;
99 private final OnCompletionListener mBeepListener = new BeepListener();
102 public void onCreate(Bundle icicle) {
103 Log.i(TAG, "Creating CaptureActivity");
104 super.onCreate(icicle);
106 Window window = getWindow();
107 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
108 setContentView(R.layout.capture);
110 CameraManager.init(getApplication());
111 mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
112 mResultView = findViewById(R.id.result_view);
113 mStatusView = findViewById(R.id.status_view);
118 showHelpOnFirstLaunch();
122 protected void onResume() {
125 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
126 SurfaceHolder surfaceHolder = surfaceView.getHolder();
128 // The activity was paused but not stopped, so the surface still exists. Therefore
129 // surfaceCreated() won't be called, so init the camera here.
130 initCamera(surfaceHolder);
132 // Install the callback and wait for surfaceCreated() to init the camera.
133 surfaceHolder.addCallback(this);
134 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
137 Intent intent = getIntent();
138 String action = intent.getAction();
139 if (intent != null && action != null && (action.equals(Intents.Scan.ACTION) ||
140 action.equals(Intents.Scan.DEPRECATED_ACTION))) {
142 mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
147 if (mLastResult == null) {
152 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
153 mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
154 mVibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
155 mCopyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
160 protected void onPause() {
162 if (mHandler != null) {
163 mHandler.quitSynchronously();
166 CameraManager.get().closeDriver();
170 public boolean onKeyDown(int keyCode, KeyEvent event) {
171 if (keyCode == KeyEvent.KEYCODE_BACK) {
173 setResult(RESULT_CANCELED);
176 } else if (mLastResult != null) {
178 mHandler.sendEmptyMessage(R.id.restart_preview);
181 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
182 // Handle these events so they don't launch the Camera app
185 return super.onKeyDown(keyCode, event);
189 public boolean onCreateOptionsMenu(Menu menu) {
190 super.onCreateOptionsMenu(menu);
191 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
192 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
193 .setIcon(android.R.drawable.ic_menu_preferences);
194 menu.add(0, HELP_ID, 0, R.string.menu_help)
195 .setIcon(android.R.drawable.ic_menu_help);
196 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
197 .setIcon(android.R.drawable.ic_menu_info_details);
201 // Don't display the share menu item if the result overlay is showing.
203 public boolean onPrepareOptionsMenu(Menu menu) {
204 super.onPrepareOptionsMenu(menu);
205 menu.findItem(SHARE_ID).setVisible(mLastResult == null);
210 public boolean onOptionsItemSelected(MenuItem item) {
211 switch (item.getItemId()) {
213 Intent intent = new Intent(Intent.ACTION_VIEW);
214 intent.setClassName(this, ShareActivity.class.getName());
215 startActivity(intent);
219 Intent intent = new Intent(Intent.ACTION_VIEW);
220 intent.setClassName(this, PreferencesActivity.class.getName());
221 startActivity(intent);
225 Intent intent = new Intent(Intent.ACTION_VIEW);
226 intent.setClassName(this, HelpActivity.class.getName());
227 startActivity(intent);
231 AlertDialog.Builder builder = new AlertDialog.Builder(this);
232 builder.setTitle(R.string.title_about);
233 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
234 builder.setIcon(R.drawable.zxing_icon);
235 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
236 builder.setNegativeButton(R.string.button_cancel, null);
240 return super.onOptionsItemSelected(item);
244 public void onConfigurationChanged(Configuration config) {
245 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
246 super.onConfigurationChanged(config);
249 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
250 public void onClick(android.content.DialogInterface dialogInterface, int i) {
251 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
252 startActivity(intent);
256 public void surfaceCreated(SurfaceHolder holder) {
263 public void surfaceDestroyed(SurfaceHolder holder) {
267 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
272 * A valid barcode has been found, so give an indication of success and show the results.
274 * @param rawResult The contents of the barcode.
275 * @param barcode A greyscale bitmap of the camera data which was decoded.
276 * @param duration How long the decoding took in milliseconds.
278 public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
279 mLastResult = rawResult;
280 playBeepSoundAndVibrate();
281 drawResultPoints(barcode, rawResult);
284 handleDecodeForScanIntent(rawResult, barcode, duration);
286 mStatusView.setVisibility(View.GONE);
287 mViewfinderView.setVisibility(View.GONE);
288 mResultView.setVisibility(View.VISIBLE);
290 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
291 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
292 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
293 barcodeImageView.setImageBitmap(barcode);
295 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
296 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
297 rawResult.getBarcodeFormat().toString());
299 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
300 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
301 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
302 resultHandler.getType().toString());
304 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
305 CharSequence title = getString(resultHandler.getDisplayTitle());
306 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
307 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
308 CharSequence displayContents = resultHandler.getDisplayContents();
309 styled.append(displayContents);
310 contentsTextView.setText(styled);
312 int buttonCount = resultHandler.getButtonCount();
313 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
314 buttonView.requestFocus();
315 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
316 Button button = (Button) buttonView.getChildAt(x);
317 if (x < buttonCount) {
318 button.setVisibility(View.VISIBLE);
319 button.setText(resultHandler.getButtonText(x));
320 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
322 button.setVisibility(View.GONE);
326 if (mCopyToClipboard) {
327 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
328 clipboard.setText(displayContents);
334 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
336 * @param barcode A bitmap of the captured image.
337 * @param rawResult The decoded results which contains the points to draw.
339 private void drawResultPoints(Bitmap barcode, Result rawResult) {
340 ResultPoint[] points = rawResult.getResultPoints();
341 if (points != null && points.length > 0) {
342 Canvas canvas = new Canvas(barcode);
343 Paint paint = new Paint();
344 paint.setColor(getResources().getColor(R.color.result_image_border));
345 paint.setStrokeWidth(3);
346 paint.setStyle(Paint.Style.STROKE);
347 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
348 canvas.drawRect(border, paint);
350 paint.setColor(getResources().getColor(R.color.result_points));
351 if (points.length == 2) {
352 paint.setStrokeWidth(4);
353 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
354 points[1].getY(), paint);
356 paint.setStrokeWidth(10);
357 for (int x = 0; x < points.length; x++) {
358 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
364 private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
365 mViewfinderView.drawResultBitmap(barcode);
367 // Since this message will only be shown for a second, just tell the user what kind of
368 // barcode was found (e.g. contact info) rather than the full contents, which they won't
369 // have time to read.
370 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
371 TextView textView = (TextView) findViewById(R.id.status_text_view);
372 textView.setGravity(Gravity.CENTER);
373 textView.setTextSize(18.0f);
374 textView.setText(getString(resultHandler.getDisplayTitle()));
376 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
378 if (mCopyToClipboard) {
379 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
380 clipboard.setText(resultHandler.getDisplayContents());
383 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
384 // the deprecated intent is retired.
385 Intent intent = new Intent(getIntent().getAction());
386 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
387 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
388 Message message = Message.obtain(mHandler, R.id.return_scan_result);
389 message.obj = intent;
390 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
394 * We want the help screen to be shown automatically the first time a new version of the app is
395 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
396 * it to a value stored as a preference.
398 private void showHelpOnFirstLaunch() {
400 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
401 int currentVersion = info.versionCode;
402 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
403 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
404 if (currentVersion > lastVersion) {
405 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
406 Intent intent = new Intent(Intent.ACTION_VIEW);
407 intent.setClassName(this, HelpActivity.class.getName());
408 startActivity(intent);
410 } catch (PackageManager.NameNotFoundException e) {
416 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
419 private void initBeepSound() {
420 if (mPlayBeep && mMediaPlayer == null) {
421 mMediaPlayer = new MediaPlayer();
422 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
423 mMediaPlayer.setOnCompletionListener(mBeepListener);
425 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
427 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
430 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
431 mMediaPlayer.prepare();
432 } catch (IOException e) {
438 private void playBeepSoundAndVibrate() {
439 if (mPlayBeep && mMediaPlayer != null) {
440 mMediaPlayer.start();
443 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
444 vibrator.vibrate(VIBRATE_DURATION);
448 private void initCamera(SurfaceHolder surfaceHolder) {
449 CameraManager.get().openDriver(surfaceHolder);
450 if (mHandler == null) {
451 boolean beginScanning = mLastResult == null;
452 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
456 private void resetStatusView() {
457 mResultView.setVisibility(View.GONE);
458 mStatusView.setVisibility(View.VISIBLE);
459 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
460 mViewfinderView.setVisibility(View.VISIBLE);
462 TextView textView = (TextView) findViewById(R.id.status_text_view);
463 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
464 textView.setTextSize(14.0f);
465 textView.setText(R.string.msg_default_status);
469 public void drawViewfinder() {
470 mViewfinderView.drawViewfinder();
474 * When the beep has finished playing, rewind to queue up another one.
476 private static class BeepListener implements OnCompletionListener {
477 public void onCompletion(MediaPlayer mediaPlayer) {
478 mediaPlayer.seekTo(0);