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 com.google.zxing.BarcodeFormat;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
22 import com.google.zxing.client.android.camera.CameraManager;
23 import com.google.zxing.client.android.history.HistoryManager;
24 import com.google.zxing.client.android.result.ResultButtonListener;
25 import com.google.zxing.client.android.result.ResultHandler;
26 import com.google.zxing.client.android.result.ResultHandlerFactory;
27 import com.google.zxing.client.android.share.ShareActivity;
29 import android.app.Activity;
30 import android.app.AlertDialog;
31 import android.content.DialogInterface;
32 import android.content.Intent;
33 import android.content.SharedPreferences;
34 import android.content.pm.PackageInfo;
35 import android.content.pm.PackageManager;
36 import android.content.res.AssetFileDescriptor;
37 import android.content.res.Configuration;
38 import android.graphics.Bitmap;
39 import android.graphics.Canvas;
40 import android.graphics.Paint;
41 import android.graphics.Rect;
42 import android.media.AudioManager;
43 import android.media.MediaPlayer;
44 import android.media.MediaPlayer.OnCompletionListener;
45 import android.net.Uri;
46 import android.os.Bundle;
47 import android.os.Handler;
48 import android.os.Message;
49 import android.os.Vibrator;
50 import android.preference.PreferenceManager;
51 import android.text.ClipboardManager;
52 import android.text.SpannableStringBuilder;
53 import android.text.style.UnderlineSpan;
54 import android.util.Log;
55 import android.view.Gravity;
56 import android.view.KeyEvent;
57 import android.view.Menu;
58 import android.view.MenuItem;
59 import android.view.SurfaceHolder;
60 import android.view.SurfaceView;
61 import android.view.View;
62 import android.view.ViewGroup;
63 import android.view.Window;
64 import android.view.WindowManager;
65 import android.widget.ImageView;
66 import android.widget.TextView;
68 import java.io.IOException;
69 import java.text.DateFormat;
70 import java.util.Arrays;
71 import java.util.List;
72 import java.util.Date;
73 import java.util.Vector;
74 import java.util.regex.Pattern;
77 * The barcode reader activity itself. This is loosely based on the CameraPreview
78 * example included in the Android SDK.
80 * @author dswitkin@google.com (Daniel Switkin)
82 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
84 private static final String TAG = CaptureActivity.class.getSimpleName();
86 private static final Pattern COMMA_PATTERN = Pattern.compile(",");
88 private static final int SHARE_ID = Menu.FIRST;
89 private static final int HISTORY_ID = Menu.FIRST + 1;
90 private static final int SETTINGS_ID = Menu.FIRST + 2;
91 private static final int HELP_ID = Menu.FIRST + 3;
92 private static final int ABOUT_ID = Menu.FIRST + 4;
94 private static final long INTENT_RESULT_DURATION = 1500L;
95 private static final float BEEP_VOLUME = 0.10f;
96 private static final long VIBRATE_DURATION = 200L;
98 private static final String PACKAGE_NAME = "com.google.zxing.client.android";
99 private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
100 private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
101 private static final String ZXING_URL = "http://zxing.appspot.com/scan";
102 private static final String RETURN_CODE_PLACEHOLDER = "{CODE}";
103 private static final String RETURN_URL_PARAM = "ret";
105 static final Vector<BarcodeFormat> PRODUCT_FORMATS;
106 static final Vector<BarcodeFormat> ONE_D_FORMATS;
107 static final Vector<BarcodeFormat> QR_CODE_FORMATS;
108 static final Vector<BarcodeFormat> ALL_FORMATS;
111 PRODUCT_FORMATS = new Vector<BarcodeFormat>(5);
112 PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
113 PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
114 PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
115 PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
116 PRODUCT_FORMATS.add(BarcodeFormat.RSS14);
117 ONE_D_FORMATS = new Vector<BarcodeFormat>(PRODUCT_FORMATS.size() + 3);
118 ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
119 ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
120 ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
121 ONE_D_FORMATS.add(BarcodeFormat.ITF);
122 QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
123 QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
124 ALL_FORMATS = new Vector<BarcodeFormat>(ONE_D_FORMATS.size() + QR_CODE_FORMATS.size());
125 ALL_FORMATS.addAll(ONE_D_FORMATS);
126 ALL_FORMATS.addAll(QR_CODE_FORMATS);
129 private enum Source {
136 private CaptureActivityHandler handler;
138 private ViewfinderView viewfinderView;
139 private View statusView;
140 private View resultView;
141 private MediaPlayer mediaPlayer;
142 private Result lastResult;
143 private boolean hasSurface;
144 private boolean playBeep;
145 private boolean vibrate;
146 private boolean copyToClipboard;
147 private Source source;
148 private String sourceUrl;
149 private String returnUrlTemplate;
150 private Vector<BarcodeFormat> decodeFormats;
151 private String characterSet;
152 private String versionName;
153 private HistoryManager historyManager;
155 private final OnCompletionListener beepListener = new BeepListener();
157 private final DialogInterface.OnClickListener aboutListener =
158 new DialogInterface.OnClickListener() {
159 public void onClick(DialogInterface dialogInterface, int i) {
160 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
161 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
162 startActivity(intent);
166 ViewfinderView getViewfinderView() {
167 return viewfinderView;
170 public Handler getHandler() {
175 public void onCreate(Bundle icicle) {
176 super.onCreate(icicle);
178 Window window = getWindow();
179 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
180 setContentView(R.layout.capture);
182 CameraManager.init(getApplication());
183 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
184 resultView = findViewById(R.id.result_view);
185 statusView = findViewById(R.id.status_view);
189 historyManager = new HistoryManager(this);
190 historyManager.trimHistory();
192 showHelpOnFirstLaunch();
196 protected void onResume() {
199 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
200 SurfaceHolder surfaceHolder = surfaceView.getHolder();
202 // The activity was paused but not stopped, so the surface still exists. Therefore
203 // surfaceCreated() won't be called, so init the camera here.
204 initCamera(surfaceHolder);
206 // Install the callback and wait for surfaceCreated() to init the camera.
207 surfaceHolder.addCallback(this);
208 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
211 Intent intent = getIntent();
212 String action = intent == null ? null : intent.getAction();
213 String dataString = intent == null ? null : intent.getDataString();
214 if (intent != null && action != null) {
215 if (action.equals(Intents.Scan.ACTION)) {
216 // Scan the formats the intent requested, and return the result to the calling activity.
217 source = Source.NATIVE_APP_INTENT;
218 decodeFormats = parseDecodeFormats(intent);
220 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
221 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
222 // Scan only products and send the result to mobile Product Search.
223 source = Source.PRODUCT_SEARCH_LINK;
224 sourceUrl = dataString;
225 decodeFormats = PRODUCT_FORMATS;
227 } else if (dataString != null && dataString.startsWith(ZXING_URL)) {
228 // Scan formats requested in query string (all formats if none specified).
229 // If a return URL is specified, send the results there. Otherwise, handle the results ourselves.
230 source = Source.ZXING_LINK;
231 sourceUrl = dataString;
232 Uri inputUri = Uri.parse(sourceUrl);
233 returnUrlTemplate = inputUri.getQueryParameter(RETURN_URL_PARAM);
234 decodeFormats = parseDecodeFormats(inputUri);
237 // Scan all formats and handle the results ourselves (launched from Home).
238 source = Source.NONE;
239 decodeFormats = null;
242 characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
244 source = Source.NONE;
245 decodeFormats = null;
247 if (lastResult == null) {
252 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
253 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
254 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
255 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
259 private static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
260 return parseDecodeFormats(
261 Arrays.asList(COMMA_PATTERN.split(intent.getStringExtra(Intents.Scan.SCAN_FORMATS))),
262 intent.getStringExtra(Intents.Scan.MODE));
265 private static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
266 List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
267 if (formats.size() == 1){
268 formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
270 return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
273 private static Vector<BarcodeFormat> parseDecodeFormats(List<String> scanFormats,
275 if (scanFormats != null) {
276 Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
278 for (String format : scanFormats) {
279 formats.add(BarcodeFormat.valueOf(format));
282 } catch (IllegalArgumentException iae) {
286 if (decodeMode != null) {
287 if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
288 return PRODUCT_FORMATS;
290 if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
291 return QR_CODE_FORMATS;
293 if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
294 return ONE_D_FORMATS;
301 protected void onPause() {
303 if (handler != null) {
304 handler.quitSynchronously();
307 CameraManager.get().closeDriver();
311 public boolean onKeyDown(int keyCode, KeyEvent event) {
312 if (keyCode == KeyEvent.KEYCODE_BACK) {
313 if (source == Source.NATIVE_APP_INTENT) {
314 setResult(RESULT_CANCELED);
317 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
319 if (handler != null) {
320 handler.sendEmptyMessage(R.id.restart_preview);
324 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
325 // Handle these events so they don't launch the Camera app
328 return super.onKeyDown(keyCode, event);
332 public boolean onCreateOptionsMenu(Menu menu) {
333 super.onCreateOptionsMenu(menu);
334 menu.add(0, SHARE_ID, 0, R.string.menu_share)
335 .setIcon(android.R.drawable.ic_menu_share);
336 menu.add(0, HISTORY_ID, 0, R.string.menu_history)
337 .setIcon(android.R.drawable.ic_menu_recent_history);
338 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
339 .setIcon(android.R.drawable.ic_menu_preferences);
340 menu.add(0, HELP_ID, 0, R.string.menu_help)
341 .setIcon(android.R.drawable.ic_menu_help);
342 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
343 .setIcon(android.R.drawable.ic_menu_info_details);
347 // Don't display the share menu item if the result overlay is showing.
349 public boolean onPrepareOptionsMenu(Menu menu) {
350 super.onPrepareOptionsMenu(menu);
351 menu.findItem(SHARE_ID).setVisible(lastResult == null);
356 public boolean onOptionsItemSelected(MenuItem item) {
357 switch (item.getItemId()) {
359 Intent intent = new Intent(Intent.ACTION_VIEW);
360 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
361 intent.setClassName(this, ShareActivity.class.getName());
362 startActivity(intent);
366 AlertDialog historyAlert = historyManager.buildAlert();
371 Intent intent = new Intent(Intent.ACTION_VIEW);
372 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
373 intent.setClassName(this, PreferencesActivity.class.getName());
374 startActivity(intent);
378 Intent intent = new Intent(Intent.ACTION_VIEW);
379 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
380 intent.setClassName(this, HelpActivity.class.getName());
381 startActivity(intent);
385 AlertDialog.Builder builder = new AlertDialog.Builder(this);
386 builder.setTitle(getString(R.string.title_about) + versionName);
387 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
388 builder.setIcon(R.drawable.zxing_icon);
389 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
390 builder.setNegativeButton(R.string.button_cancel, null);
394 return super.onOptionsItemSelected(item);
398 public void onConfigurationChanged(Configuration config) {
399 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
400 super.onConfigurationChanged(config);
403 public void surfaceCreated(SurfaceHolder holder) {
410 public void surfaceDestroyed(SurfaceHolder holder) {
414 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
419 * A valid barcode has been found, so give an indication of success and show the results.
421 * @param rawResult The contents of the barcode.
422 * @param barcode A greyscale bitmap of the camera data which was decoded.
424 public void handleDecode(Result rawResult, Bitmap barcode) {
425 lastResult = rawResult;
426 historyManager.addHistoryItem(rawResult);
427 if (barcode == null) {
428 // This is from history -- no saved barcode
429 handleDecodeInternally(rawResult, null);
431 playBeepSoundAndVibrate();
432 drawResultPoints(barcode, rawResult);
434 case NATIVE_APP_INTENT:
435 case PRODUCT_SEARCH_LINK:
436 handleDecodeExternally(rawResult, barcode);
439 if(returnUrlTemplate == null){
440 handleDecodeInternally(rawResult, barcode);
442 handleDecodeExternally(rawResult, barcode);
446 handleDecodeInternally(rawResult, barcode);
453 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
455 * @param barcode A bitmap of the captured image.
456 * @param rawResult The decoded results which contains the points to draw.
458 private void drawResultPoints(Bitmap barcode, Result rawResult) {
459 ResultPoint[] points = rawResult.getResultPoints();
460 if (points != null && points.length > 0) {
461 Canvas canvas = new Canvas(barcode);
462 Paint paint = new Paint();
463 paint.setColor(getResources().getColor(R.color.result_image_border));
464 paint.setStrokeWidth(3.0f);
465 paint.setStyle(Paint.Style.STROKE);
466 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
467 canvas.drawRect(border, paint);
469 paint.setColor(getResources().getColor(R.color.result_points));
470 if (points.length == 2) {
471 paint.setStrokeWidth(4.0f);
472 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
473 points[1].getY(), paint);
475 paint.setStrokeWidth(10.0f);
476 for (ResultPoint point : points) {
477 canvas.drawPoint(point.getX(), point.getY(), paint);
483 // Put up our own UI for how to handle the decoded contents.
484 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
485 statusView.setVisibility(View.GONE);
486 viewfinderView.setVisibility(View.GONE);
487 resultView.setVisibility(View.VISIBLE);
489 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
490 if (barcode == null) {
491 barcodeImageView.setImageResource(R.drawable.zxing_icon);
493 barcodeImageView.setImageBitmap(barcode);
495 barcodeImageView.setVisibility(View.VISIBLE);
497 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
498 formatTextView.setVisibility(View.VISIBLE);
499 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
500 rawResult.getBarcodeFormat().toString());
502 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
503 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
504 typeTextView.setVisibility(View.VISIBLE);
505 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
506 resultHandler.getType().toString());
508 DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
509 String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
510 TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
511 timeTextView.setVisibility(View.VISIBLE);
512 timeTextView.setText(getString(R.string.msg_default_time) + ": " + formattedTime);
514 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
515 CharSequence title = getString(resultHandler.getDisplayTitle());
516 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
517 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
518 CharSequence displayContents = resultHandler.getDisplayContents();
519 styled.append(displayContents);
520 contentsTextView.setText(styled);
522 int buttonCount = resultHandler.getButtonCount();
523 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
524 buttonView.requestFocus();
525 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
526 TextView button = (TextView) buttonView.getChildAt(x);
527 if (x < buttonCount) {
528 button.setVisibility(View.VISIBLE);
529 button.setText(resultHandler.getButtonText(x));
530 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
532 button.setVisibility(View.GONE);
536 if (copyToClipboard) {
537 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
538 clipboard.setText(displayContents);
542 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
543 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
544 viewfinderView.drawResultBitmap(barcode);
546 // Since this message will only be shown for a second, just tell the user what kind of
547 // barcode was found (e.g. contact info) rather than the full contents, which they won't
548 // have time to read.
549 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
550 TextView textView = (TextView) findViewById(R.id.status_text_view);
551 textView.setGravity(Gravity.CENTER);
552 textView.setTextSize(18.0f);
553 textView.setText(getString(resultHandler.getDisplayTitle()));
555 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
557 if (copyToClipboard) {
558 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
559 clipboard.setText(resultHandler.getDisplayContents());
562 if (source == Source.NATIVE_APP_INTENT) {
563 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
564 // the deprecated intent is retired.
565 Intent intent = new Intent(getIntent().getAction());
566 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
567 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
568 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
569 Message message = Message.obtain(handler, R.id.return_scan_result);
570 message.obj = intent;
571 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
572 } else if (source == Source.PRODUCT_SEARCH_LINK) {
573 // Reformulate the URL which triggered us into a query, so that the request goes to the same
574 // TLD as the scan URL.
575 Message message = Message.obtain(handler, R.id.launch_product_query);
576 int end = sourceUrl.lastIndexOf("/scan");
577 message.obj = sourceUrl.substring(0, end) + "?q=" +
578 resultHandler.getDisplayContents().toString() + "&source=zxing";
579 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
580 } else if (source == Source.ZXING_LINK) {
581 // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate
582 // with the scanned code. This allows both queries and REST-style URLs to work.
583 Message message = Message.obtain(handler, R.id.launch_product_query);
584 message.obj = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER, resultHandler.getDisplayContents().toString());
585 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
590 * We want the help screen to be shown automatically the first time a new version of the app is
591 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
592 * it to a value stored as a preference.
594 private boolean showHelpOnFirstLaunch() {
596 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
597 int currentVersion = info.versionCode;
598 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
599 // version name here for display in the about box later.
600 this.versionName = info.versionName;
601 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
602 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
603 if (currentVersion > lastVersion) {
604 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
605 Intent intent = new Intent(this, HelpActivity.class);
606 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
607 // Show the default page on a clean install, and the what's new page on an upgrade.
608 String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
609 intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
610 startActivity(intent);
613 } catch (PackageManager.NameNotFoundException e) {
620 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
623 private void initBeepSound() {
624 if (playBeep && mediaPlayer == null) {
625 // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
626 // so we now play on the music stream.
627 setVolumeControlStream(AudioManager.STREAM_MUSIC);
628 mediaPlayer = new MediaPlayer();
629 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
630 mediaPlayer.setOnCompletionListener(beepListener);
632 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
634 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
637 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
638 mediaPlayer.prepare();
639 } catch (IOException e) {
645 private void playBeepSoundAndVibrate() {
646 if (playBeep && mediaPlayer != null) {
650 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
651 vibrator.vibrate(VIBRATE_DURATION);
655 private void initCamera(SurfaceHolder surfaceHolder) {
657 CameraManager.get().openDriver(surfaceHolder);
658 } catch (IOException ioe) {
660 displayFrameworkBugMessageAndExit();
662 } catch (RuntimeException e) {
663 // Barcode Scanner has seen crashes in the wild of this variety:
664 // java.?lang.?RuntimeException: Fail to connect to camera service
665 Log.e(TAG, e.toString());
666 displayFrameworkBugMessageAndExit();
669 if (handler == null) {
670 boolean beginScanning = lastResult == null;
671 handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
675 private void displayFrameworkBugMessageAndExit() {
676 AlertDialog.Builder builder = new AlertDialog.Builder(this);
677 builder.setTitle(getString(R.string.app_name));
678 builder.setMessage(getString(R.string.msg_camera_framework_bug));
679 builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
680 public void onClick(DialogInterface dialogInterface, int i) {
687 private void resetStatusView() {
688 resultView.setVisibility(View.GONE);
689 statusView.setVisibility(View.VISIBLE);
690 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
691 viewfinderView.setVisibility(View.VISIBLE);
693 TextView textView = (TextView) findViewById(R.id.status_text_view);
694 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
695 textView.setTextSize(14.0f);
696 textView.setText(R.string.msg_default_status);
700 public void drawViewfinder() {
701 viewfinderView.drawViewfinder();
705 * When the beep has finished playing, rewind to queue up another one.
707 private static class BeepListener implements OnCompletionListener {
708 public void onCompletion(MediaPlayer mediaPlayer) {
709 mediaPlayer.seekTo(0);