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.preference.PreferenceManager;
39 import android.text.SpannableStringBuilder;
40 import android.text.style.UnderlineSpan;
41 import android.view.Gravity;
42 import android.view.KeyEvent;
43 import android.view.Menu;
44 import android.view.MenuItem;
45 import android.view.SurfaceHolder;
46 import android.view.SurfaceView;
47 import android.view.View;
48 import android.view.ViewGroup;
49 import android.view.Window;
50 import android.view.WindowManager;
51 import android.widget.Button;
52 import android.widget.ImageView;
53 import android.widget.TextView;
54 import com.google.zxing.Result;
55 import com.google.zxing.ResultPoint;
56 import com.google.zxing.client.android.result.ResultButtonListener;
57 import com.google.zxing.client.android.result.ResultHandler;
58 import com.google.zxing.client.android.result.ResultHandlerFactory;
60 import java.io.IOException;
63 * The barcode reader activity itself. This is loosely based on the CameraPreview
64 * example included in the Android SDK.
66 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
68 private static final int SHARE_ID = Menu.FIRST;
69 private static final int SETTINGS_ID = Menu.FIRST + 1;
70 private static final int HELP_ID = Menu.FIRST + 2;
71 private static final int ABOUT_ID = Menu.FIRST + 3;
73 private static final int MAX_RESULT_IMAGE_SIZE = 150;
74 private static final int INTENT_RESULT_DURATION = 1500;
75 private static final float BEEP_VOLUME = 0.15f;
77 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
79 public CaptureActivityHandler mHandler;
81 private ViewfinderView mViewfinderView;
82 private View mStatusView;
83 private View mResultView;
84 private MediaPlayer mMediaPlayer;
85 private Result mLastResult;
86 private boolean mHasSurface;
87 private boolean mPlayBeep;
88 private boolean mScanIntent;
89 private String mDecodeMode;
91 private final OnCompletionListener mBeepListener = new BeepListener();
94 public void onCreate(Bundle icicle) {
95 super.onCreate(icicle);
97 Window window = getWindow();
98 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
99 setContentView(R.layout.capture);
101 CameraManager.init(getApplication());
102 mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
103 mResultView = findViewById(R.id.result_view);
104 mStatusView = findViewById(R.id.status_view);
109 showHelpOnFirstLaunch();
113 protected void onResume() {
116 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
117 SurfaceHolder surfaceHolder = surfaceView.getHolder();
119 // The activity was paused but not stopped, so the surface still exists. Therefore
120 // surfaceCreated() won't be called, so init the camera here.
121 initCamera(surfaceHolder);
123 // Install the callback and wait for surfaceCreated() to init the camera.
124 surfaceHolder.addCallback(this);
125 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
128 Intent intent = getIntent();
129 if (intent != null && (intent.getAction().equals(Intents.Scan.ACTION) ||
130 intent.getAction().equals(Intents.Scan.DEPRECATED_ACTION))) {
132 mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
137 if (mLastResult == null) {
142 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
143 mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
148 protected void onPause() {
150 if (mHandler != null) {
151 mHandler.quitSynchronously();
154 CameraManager.get().closeDriver();
158 public boolean onKeyDown(int keyCode, KeyEvent event) {
159 if (keyCode == KeyEvent.KEYCODE_BACK) {
161 setResult(RESULT_CANCELED);
164 } else if (mLastResult != null) {
166 mHandler.sendEmptyMessage(R.id.restart_preview);
169 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
170 // Handle these events so they don't launch the Camera app
173 return super.onKeyDown(keyCode, event);
177 public boolean onCreateOptionsMenu(Menu menu) {
178 super.onCreateOptionsMenu(menu);
179 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
180 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
181 .setIcon(android.R.drawable.ic_menu_preferences);
182 menu.add(0, HELP_ID, 0, R.string.menu_help)
183 .setIcon(android.R.drawable.ic_menu_help);
184 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
185 .setIcon(android.R.drawable.ic_menu_info_details);
189 // Don't display the share menu item if the result overlay is showing.
191 public boolean onPrepareOptionsMenu(Menu menu) {
192 super.onPrepareOptionsMenu(menu);
193 menu.findItem(SHARE_ID).setVisible(mLastResult == null);
198 public boolean onOptionsItemSelected(MenuItem item) {
199 switch (item.getItemId()) {
201 Intent intent = new Intent(Intent.ACTION_VIEW);
202 intent.setClassName(this, ShareActivity.class.getName());
203 startActivity(intent);
207 Intent intent = new Intent(Intent.ACTION_VIEW);
208 intent.setClassName(this, PreferencesActivity.class.getName());
209 startActivity(intent);
213 Intent intent = new Intent(Intent.ACTION_VIEW);
214 intent.setClassName(this, HelpActivity.class.getName());
215 startActivity(intent);
219 AlertDialog.Builder builder = new AlertDialog.Builder(this);
220 builder.setTitle(R.string.title_about);
221 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
222 builder.setIcon(R.drawable.zxing_icon);
223 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
224 builder.setNegativeButton(R.string.button_cancel, null);
229 return super.onOptionsItemSelected(item);
233 public void onConfigurationChanged(Configuration config) {
234 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
235 super.onConfigurationChanged(config);
238 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
239 public void onClick(android.content.DialogInterface dialogInterface, int i) {
240 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
241 startActivity(intent);
245 public void surfaceCreated(SurfaceHolder holder) {
252 public void surfaceDestroyed(SurfaceHolder holder) {
256 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
261 * A valid barcode has been found, so give an indication of success and show the results.
263 * @param rawResult The contents of the barcode.
264 * @param barcode A greyscale bitmap of the camera data which was decoded.
265 * @param duration How long the decoding took in milliseconds.
267 public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
268 mLastResult = rawResult;
270 drawResultPoints(barcode, rawResult);
273 handleDecodeForScanIntent(rawResult, barcode, duration);
275 mStatusView.setVisibility(View.GONE);
276 mViewfinderView.setVisibility(View.GONE);
277 mResultView.setVisibility(View.VISIBLE);
279 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
280 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
281 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
282 barcodeImageView.setImageBitmap(barcode);
284 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
285 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
286 rawResult.getBarcodeFormat().toString());
288 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
289 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
290 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
291 resultHandler.getType().toString());
293 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
294 CharSequence title = getString(resultHandler.getDisplayTitle());
295 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
296 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
297 styled.append(resultHandler.getDisplayContents());
298 contentsTextView.setText(styled);
300 int buttonCount = resultHandler.getButtonCount();
301 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
302 buttonView.requestFocus();
303 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
304 Button button = (Button) buttonView.getChildAt(x);
305 if (x < buttonCount) {
306 button.setVisibility(View.VISIBLE);
307 button.setText(resultHandler.getButtonText(x));
308 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
310 button.setVisibility(View.GONE);
317 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
319 * @param barcode A bitmap of the captured image.
320 * @param rawResult The decoded results which contains the points to draw.
322 private void drawResultPoints(Bitmap barcode, Result rawResult) {
323 ResultPoint[] points = rawResult.getResultPoints();
324 if (points != null && points.length > 0) {
325 Canvas canvas = new Canvas(barcode);
326 Paint paint = new Paint();
327 paint.setColor(getResources().getColor(R.color.result_image_border));
328 paint.setStrokeWidth(3);
329 paint.setStyle(Paint.Style.STROKE);
330 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
331 canvas.drawRect(border, paint);
333 paint.setColor(getResources().getColor(R.color.result_points));
334 if (points.length == 2) {
335 paint.setStrokeWidth(4);
336 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
337 points[1].getY(), paint);
339 paint.setStrokeWidth(10);
340 for (int x = 0; x < points.length; x++) {
341 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
347 private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
348 mViewfinderView.drawResultBitmap(barcode);
350 // Since this message will only be shown for a second, just tell the user what kind of
351 // barcode was found (e.g. contact info) rather than the full contents, which they won't
352 // have time to read.
353 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
354 TextView textView = (TextView) findViewById(R.id.status_text_view);
355 textView.setGravity(Gravity.CENTER);
356 textView.setTextSize(18.0f);
357 textView.setText(getString(resultHandler.getDisplayTitle()));
359 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
361 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
362 // the deprecated intent is retired.
363 Intent intent = new Intent(getIntent().getAction());
364 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
365 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
366 Message message = Message.obtain(mHandler, R.id.return_scan_result);
367 message.obj = intent;
368 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
372 * We want the help screen to be shown automatically the first time a new version of the app is
373 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
374 * it to a value stored as a preference.
376 private void showHelpOnFirstLaunch() {
378 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
379 int currentVersion = info.versionCode;
380 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
381 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
382 if (currentVersion > lastVersion) {
383 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
384 Intent intent = new Intent(Intent.ACTION_VIEW);
385 intent.setClassName(this, HelpActivity.class.getName());
386 startActivity(intent);
388 } catch (PackageManager.NameNotFoundException e) {
394 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
397 private void initBeepSound() {
398 if (mPlayBeep && mMediaPlayer == null) {
399 mMediaPlayer = new MediaPlayer();
400 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
401 mMediaPlayer.setOnCompletionListener(mBeepListener);
403 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
405 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
408 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
409 mMediaPlayer.prepare();
410 } catch (IOException e) {
416 private void playBeepSound() {
417 if (mPlayBeep && mMediaPlayer != null) {
418 mMediaPlayer.start();
422 private void initCamera(SurfaceHolder surfaceHolder) {
423 CameraManager.get().openDriver(surfaceHolder);
424 if (mHandler == null) {
425 boolean beginScanning = mLastResult == null;
426 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
430 private void resetStatusView() {
431 mResultView.setVisibility(View.GONE);
432 mStatusView.setVisibility(View.VISIBLE);
433 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
434 mViewfinderView.setVisibility(View.VISIBLE);
436 TextView textView = (TextView) findViewById(R.id.status_text_view);
437 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
438 textView.setTextSize(14.0f);
439 textView.setText(R.string.msg_default_status);
443 public void drawViewfinder() {
444 mViewfinderView.drawViewfinder();
448 * When the beep has finished playing, rewind to queue up another one.
450 private static class BeepListener implements OnCompletionListener {
451 public void onCompletion(MediaPlayer mediaPlayer) {
452 mediaPlayer.seekTo(0);