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.res.AssetFileDescriptor;
25 import android.content.res.Configuration;
26 import android.graphics.Bitmap;
27 import android.graphics.Canvas;
28 import android.graphics.Paint;
29 import android.graphics.Rect;
30 import android.media.AudioManager;
31 import android.media.MediaPlayer;
32 import android.media.MediaPlayer.OnCompletionListener;
33 import android.net.Uri;
34 import android.os.Bundle;
35 import android.os.Message;
36 import android.preference.PreferenceManager;
37 import android.text.SpannableStringBuilder;
38 import android.text.style.UnderlineSpan;
39 import android.view.Gravity;
40 import android.view.KeyEvent;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.SurfaceHolder;
44 import android.view.SurfaceView;
45 import android.view.View;
46 import android.view.ViewGroup;
47 import android.view.Window;
48 import android.view.WindowManager;
49 import android.widget.Button;
50 import android.widget.ImageView;
51 import android.widget.TextView;
52 import com.google.zxing.Result;
53 import com.google.zxing.ResultPoint;
54 import com.google.zxing.client.android.result.ResultButtonListener;
55 import com.google.zxing.client.android.result.ResultHandler;
56 import com.google.zxing.client.android.result.ResultHandlerFactory;
58 import java.io.IOException;
61 * The barcode reader activity itself. This is loosely based on the CameraPreview
62 * example included in the Android SDK.
64 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
66 private static final int SHARE_ID = Menu.FIRST;
67 private static final int SETTINGS_ID = Menu.FIRST + 1;
68 private static final int HELP_ID = Menu.FIRST + 2;
69 private static final int ABOUT_ID = Menu.FIRST + 3;
71 private static final int MAX_RESULT_IMAGE_SIZE = 150;
72 private static final int INTENT_RESULT_DURATION = 1500;
73 private static final float BEEP_VOLUME = 0.15f;
75 public CaptureActivityHandler mHandler;
77 private ViewfinderView mViewfinderView;
78 private View mStatusView;
79 private View mResultView;
80 private MediaPlayer mMediaPlayer;
81 private Result mLastResult;
82 private boolean mHasSurface;
83 private boolean mPlayBeep;
84 private boolean mScanIntent;
85 private String mDecodeMode;
88 public void onCreate(Bundle icicle) {
89 super.onCreate(icicle);
91 Window window = getWindow();
92 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
93 setContentView(R.layout.capture);
95 CameraManager.init(getApplication());
96 mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
97 mResultView = findViewById(R.id.result_view);
98 mStatusView = findViewById(R.id.status_view);
105 protected void onResume() {
108 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
109 SurfaceHolder surfaceHolder = surfaceView.getHolder();
111 // The activity was paused but not stopped, so the surface still exists. Therefore
112 // surfaceCreated() won't be called, so init the camera here.
113 initCamera(surfaceHolder);
115 // Install the callback and wait for surfaceCreated() to init the camera.
116 surfaceHolder.addCallback(this);
117 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
120 Intent intent = getIntent();
121 if (intent != null && (intent.getAction().equals(Intents.Scan.ACTION) ||
122 intent.getAction().equals(Intents.Scan.DEPRECATED_ACTION))) {
124 mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
129 if (mLastResult == null) {
134 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
135 mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
140 protected void onPause() {
142 if (mHandler != null) {
143 mHandler.quitSynchronously();
146 CameraManager.get().closeDriver();
150 public boolean onKeyDown(int keyCode, KeyEvent event) {
151 if (keyCode == KeyEvent.KEYCODE_BACK) {
153 setResult(RESULT_CANCELED);
156 } else if (mLastResult != null) {
158 mHandler.sendEmptyMessage(R.id.restart_preview);
161 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
162 // Handle these events so they don't launch the Camera app
165 return super.onKeyDown(keyCode, event);
169 public boolean onCreateOptionsMenu(Menu menu) {
170 super.onCreateOptionsMenu(menu);
171 menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_barcode);
172 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
173 .setIcon(android.R.drawable.ic_menu_preferences);
174 menu.add(0, HELP_ID, 0, R.string.menu_help)
175 .setIcon(android.R.drawable.ic_menu_help);
176 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
177 .setIcon(android.R.drawable.ic_menu_info_details);
181 // Don't display the share menu item if the result overlay is showing.
183 public boolean onPrepareOptionsMenu(Menu menu) {
184 super.onPrepareOptionsMenu(menu);
185 menu.findItem(SHARE_ID).setVisible(mLastResult == null);
190 public boolean onOptionsItemSelected(MenuItem item) {
191 switch (item.getItemId()) {
193 Intent intent = new Intent(Intent.ACTION_VIEW);
194 intent.setClassName(this, ShareActivity.class.getName());
195 startActivity(intent);
199 Intent intent = new Intent(Intent.ACTION_VIEW);
200 intent.setClassName(this, PreferencesActivity.class.getName());
201 startActivity(intent);
205 AlertDialog.Builder builder = new AlertDialog.Builder(this);
206 builder.setTitle(R.string.title_help);
207 builder.setMessage(R.string.msg_help);
208 builder.setPositiveButton(R.string.button_ok, null);
213 AlertDialog.Builder builder = new AlertDialog.Builder(this);
214 builder.setTitle(R.string.title_about);
215 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
216 builder.setIcon(R.drawable.zxing_icon);
217 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
218 builder.setNegativeButton(R.string.button_cancel, null);
223 return super.onOptionsItemSelected(item);
227 public void onConfigurationChanged(Configuration config) {
228 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
229 super.onConfigurationChanged(config);
232 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
233 public void onClick(android.content.DialogInterface dialogInterface, int i) {
234 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
235 startActivity(intent);
239 public void surfaceCreated(SurfaceHolder holder) {
246 public void surfaceDestroyed(SurfaceHolder holder) {
250 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
255 * A valid barcode has been found, so give an indication of success and show the results.
257 * @param rawResult The contents of the barcode.
258 * @param barcode A greyscale bitmap of the camera data which was decoded.
259 * @param duration How long the decoding took in milliseconds.
261 public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
262 mLastResult = rawResult;
264 drawResultPoints(barcode, rawResult);
267 handleDecodeForScanIntent(rawResult, barcode, duration);
269 mStatusView.setVisibility(View.GONE);
270 mViewfinderView.setVisibility(View.GONE);
271 mResultView.setVisibility(View.VISIBLE);
273 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
274 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
275 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
276 barcodeImageView.setImageBitmap(barcode);
278 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
279 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
280 rawResult.getBarcodeFormat().toString());
282 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
283 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
284 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
285 resultHandler.getType().toString());
287 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
288 CharSequence title = getString(resultHandler.getDisplayTitle());
289 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
290 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
291 styled.append(resultHandler.getDisplayContents());
292 contentsTextView.setText(styled);
294 int buttonCount = resultHandler.getButtonCount();
295 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
296 buttonView.requestFocus();
297 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
298 Button button = (Button) buttonView.getChildAt(x);
299 if (x < buttonCount) {
300 button.setVisibility(View.VISIBLE);
301 button.setText(resultHandler.getButtonText(x));
302 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
304 button.setVisibility(View.GONE);
311 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
313 * @param barcode A bitmap of the captured image.
314 * @param rawResult The decoded results which contains the points to draw.
316 private void drawResultPoints(Bitmap barcode, Result rawResult) {
317 ResultPoint[] points = rawResult.getResultPoints();
318 if (points != null && points.length > 0) {
319 Canvas canvas = new Canvas(barcode);
320 Paint paint = new Paint();
321 paint.setColor(getResources().getColor(R.color.result_image_border));
322 paint.setStrokeWidth(3);
323 paint.setStyle(Paint.Style.STROKE);
324 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
325 canvas.drawRect(border, paint);
327 paint.setColor(getResources().getColor(R.color.result_points));
328 if (points.length == 2) {
329 paint.setStrokeWidth(4);
330 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
331 points[1].getY(), paint);
333 paint.setStrokeWidth(10);
334 for (int x = 0; x < points.length; x++) {
335 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
341 private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
342 mViewfinderView.drawResultBitmap(barcode);
344 // Since this message will only be shown for a second, just tell the user what kind of
345 // barcode was found (e.g. contact info) rather than the full contents, which they won't
346 // have time to read.
347 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
348 TextView textView = (TextView) findViewById(R.id.status_text_view);
349 textView.setGravity(Gravity.CENTER);
350 textView.setTextSize(18.0f);
351 textView.setText(getString(resultHandler.getDisplayTitle()));
353 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
355 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
356 // the deprecated intent is retired.
357 Intent intent = new Intent(getIntent().getAction());
358 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
359 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
360 Message message = Message.obtain(mHandler, R.id.return_scan_result);
361 message.obj = intent;
362 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
366 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
369 private void initBeepSound() {
370 if (mPlayBeep && mMediaPlayer == null) {
371 mMediaPlayer = new MediaPlayer();
372 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
373 mMediaPlayer.setOnCompletionListener(mBeepListener);
375 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
377 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
380 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
381 mMediaPlayer.prepare();
382 } catch (IOException e) {
388 private void playBeepSound() {
389 if (mPlayBeep && mMediaPlayer != null) {
390 mMediaPlayer.start();
394 private void initCamera(SurfaceHolder surfaceHolder) {
395 CameraManager.get().openDriver(surfaceHolder);
396 if (mHandler == null) {
397 boolean beginScanning = mLastResult == null;
398 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
403 * When the beep has finished playing, rewind to queue up another one.
405 private final OnCompletionListener mBeepListener = new OnCompletionListener() {
406 public void onCompletion(MediaPlayer mediaPlayer) {
407 mediaPlayer.seekTo(0);
411 private void resetStatusView() {
412 mResultView.setVisibility(View.GONE);
413 mStatusView.setVisibility(View.VISIBLE);
414 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
415 mViewfinderView.setVisibility(View.VISIBLE);
417 TextView textView = (TextView) findViewById(R.id.status_text_view);
418 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
419 textView.setTextSize(14.0f);
420 textView.setText(R.string.msg_default_status);
424 public void drawViewfinder() {
425 mViewfinderView.drawViewfinder();