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);
182 public boolean onOptionsItemSelected(MenuItem item) {
183 switch (item.getItemId()) {
185 Intent intent = new Intent(Intent.ACTION_VIEW);
186 intent.setClassName(this, ShareActivity.class.getName());
187 startActivity(intent);
191 Intent intent = new Intent(Intent.ACTION_VIEW);
192 intent.setClassName(this, PreferencesActivity.class.getName());
193 startActivity(intent);
197 AlertDialog.Builder builder = new AlertDialog.Builder(this);
198 builder.setTitle(R.string.title_help);
199 builder.setMessage(R.string.msg_help);
200 builder.setPositiveButton(R.string.button_ok, null);
205 AlertDialog.Builder builder = new AlertDialog.Builder(this);
206 builder.setTitle(R.string.title_about);
207 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
208 builder.setIcon(R.drawable.zxing_icon);
209 builder.setPositiveButton(R.string.button_open_browser, mAboutListener);
210 builder.setNegativeButton(R.string.button_cancel, null);
215 return super.onOptionsItemSelected(item);
219 public void onConfigurationChanged(Configuration config) {
220 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
221 super.onConfigurationChanged(config);
224 private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() {
225 public void onClick(android.content.DialogInterface dialogInterface, int i) {
226 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
227 startActivity(intent);
231 public void surfaceCreated(SurfaceHolder holder) {
238 public void surfaceDestroyed(SurfaceHolder holder) {
242 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
247 * A valid barcode has been found, so give an indication of success and show the results.
249 * @param rawResult The contents of the barcode.
250 * @param barcode A greyscale bitmap of the camera data which was decoded.
251 * @param duration How long the decoding took in milliseconds.
253 public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
254 mLastResult = rawResult;
256 drawResultPoints(barcode, rawResult);
259 handleDecodeForScanIntent(rawResult, barcode, duration);
261 mStatusView.setVisibility(View.GONE);
262 mViewfinderView.setVisibility(View.GONE);
263 mResultView.setVisibility(View.VISIBLE);
265 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
266 barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
267 barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
268 barcodeImageView.setImageBitmap(barcode);
270 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
271 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
272 rawResult.getBarcodeFormat().toString());
274 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
275 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
276 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
277 resultHandler.getType().toString());
279 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
280 CharSequence title = getString(resultHandler.getDisplayTitle());
281 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
282 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
283 styled.append(resultHandler.getDisplayContents());
284 contentsTextView.setText(styled);
286 int buttonCount = resultHandler.getButtonCount();
287 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
288 buttonView.requestFocus();
289 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
290 Button button = (Button) buttonView.getChildAt(x);
291 if (x < buttonCount) {
292 button.setVisibility(View.VISIBLE);
293 button.setText(resultHandler.getButtonText(x));
294 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
296 button.setVisibility(View.GONE);
303 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
305 * @param barcode A bitmap of the captured image.
306 * @param rawResult The decoded results which contains the points to draw.
308 private void drawResultPoints(Bitmap barcode, Result rawResult) {
309 ResultPoint[] points = rawResult.getResultPoints();
310 if (points != null && points.length > 0) {
311 Canvas canvas = new Canvas(barcode);
312 Paint paint = new Paint();
313 paint.setColor(getResources().getColor(R.color.result_image_border));
314 paint.setStrokeWidth(3);
315 paint.setStyle(Paint.Style.STROKE);
316 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
317 canvas.drawRect(border, paint);
319 paint.setColor(getResources().getColor(R.color.result_points));
320 if (points.length == 2) {
321 paint.setStrokeWidth(4);
322 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
323 points[1].getY(), paint);
325 paint.setStrokeWidth(10);
326 for (int x = 0; x < points.length; x++) {
327 canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
333 private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
334 mViewfinderView.drawResultBitmap(barcode);
336 // Since this message will only be shown for a second, just tell the user what kind of
337 // barcode was found (e.g. contact info) rather than the full contents, which they won't
338 // have time to read.
339 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
340 TextView textView = (TextView) findViewById(R.id.status_text_view);
341 textView.setGravity(Gravity.CENTER);
342 textView.setTextSize(18.0f);
343 textView.setText(getString(resultHandler.getDisplayTitle()));
345 mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
347 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
348 // the deprecated intent is retired.
349 Intent intent = new Intent(getIntent().getAction());
350 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
351 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
352 Message message = Message.obtain(mHandler, R.id.return_scan_result);
353 message.obj = intent;
354 mHandler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
358 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
361 private void initBeepSound() {
362 if (mPlayBeep && mMediaPlayer == null) {
363 mMediaPlayer = new MediaPlayer();
364 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
365 mMediaPlayer.setOnCompletionListener(mBeepListener);
367 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
369 mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
372 mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
373 mMediaPlayer.prepare();
374 } catch (IOException e) {
380 private void playBeepSound() {
381 if (mPlayBeep && mMediaPlayer != null) {
382 mMediaPlayer.start();
386 private void initCamera(SurfaceHolder surfaceHolder) {
387 CameraManager.get().openDriver(surfaceHolder);
388 if (mHandler == null) {
389 boolean beginScanning = mLastResult == null;
390 mHandler = new CaptureActivityHandler(this, mDecodeMode, beginScanning);
395 * When the beep has finished playing, rewind to queue up another one.
397 private final OnCompletionListener mBeepListener = new OnCompletionListener() {
398 public void onCompletion(MediaPlayer mediaPlayer) {
399 mediaPlayer.seekTo(0);
403 private void resetStatusView() {
404 mResultView.setVisibility(View.GONE);
405 mStatusView.setVisibility(View.VISIBLE);
406 mStatusView.setBackgroundColor(getResources().getColor(R.color.status_view));
407 mViewfinderView.setVisibility(View.VISIBLE);
409 TextView textView = (TextView) findViewById(R.id.status_text_view);
410 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
411 textView.setTextSize(14.0f);
412 textView.setText(R.string.msg_default_status);
416 public void drawViewfinder() {
417 mViewfinderView.drawViewfinder();