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_93);
121 ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
122 ONE_D_FORMATS.add(BarcodeFormat.ITF);
123 QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
124 QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
125 ALL_FORMATS = new Vector<BarcodeFormat>(ONE_D_FORMATS.size() + QR_CODE_FORMATS.size());
126 ALL_FORMATS.addAll(ONE_D_FORMATS);
127 ALL_FORMATS.addAll(QR_CODE_FORMATS);
130 private enum Source {
137 private CaptureActivityHandler handler;
139 private ViewfinderView viewfinderView;
140 private View statusView;
141 private View resultView;
142 private MediaPlayer mediaPlayer;
143 private Result lastResult;
144 private boolean hasSurface;
145 private boolean playBeep;
146 private boolean vibrate;
147 private boolean copyToClipboard;
148 private Source source;
149 private String sourceUrl;
150 private String returnUrlTemplate;
151 private Vector<BarcodeFormat> decodeFormats;
152 private String characterSet;
153 private String versionName;
154 private HistoryManager historyManager;
156 private final OnCompletionListener beepListener = new BeepListener();
158 private final DialogInterface.OnClickListener aboutListener =
159 new DialogInterface.OnClickListener() {
160 public void onClick(DialogInterface dialogInterface, int i) {
161 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
162 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
163 startActivity(intent);
167 ViewfinderView getViewfinderView() {
168 return viewfinderView;
171 public Handler getHandler() {
176 public void onCreate(Bundle icicle) {
177 super.onCreate(icicle);
179 Window window = getWindow();
180 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
181 setContentView(R.layout.capture);
183 CameraManager.init(getApplication());
184 viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
185 resultView = findViewById(R.id.result_view);
186 statusView = findViewById(R.id.status_view);
190 historyManager = new HistoryManager(this);
191 historyManager.trimHistory();
193 showHelpOnFirstLaunch();
197 protected void onResume() {
200 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
201 SurfaceHolder surfaceHolder = surfaceView.getHolder();
203 // The activity was paused but not stopped, so the surface still exists. Therefore
204 // surfaceCreated() won't be called, so init the camera here.
205 initCamera(surfaceHolder);
207 // Install the callback and wait for surfaceCreated() to init the camera.
208 surfaceHolder.addCallback(this);
209 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
212 Intent intent = getIntent();
213 String action = intent == null ? null : intent.getAction();
214 String dataString = intent == null ? null : intent.getDataString();
215 if (intent != null && action != null) {
216 if (action.equals(Intents.Scan.ACTION)) {
217 // Scan the formats the intent requested, and return the result to the calling activity.
218 source = Source.NATIVE_APP_INTENT;
219 decodeFormats = parseDecodeFormats(intent);
221 } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
222 dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
223 // Scan only products and send the result to mobile Product Search.
224 source = Source.PRODUCT_SEARCH_LINK;
225 sourceUrl = dataString;
226 decodeFormats = PRODUCT_FORMATS;
228 } else if (dataString != null && dataString.startsWith(ZXING_URL)) {
229 // Scan formats requested in query string (all formats if none specified).
230 // If a return URL is specified, send the results there. Otherwise, handle the results ourselves.
231 source = Source.ZXING_LINK;
232 sourceUrl = dataString;
233 Uri inputUri = Uri.parse(sourceUrl);
234 returnUrlTemplate = inputUri.getQueryParameter(RETURN_URL_PARAM);
235 decodeFormats = parseDecodeFormats(inputUri);
238 // Scan all formats and handle the results ourselves (launched from Home).
239 source = Source.NONE;
240 decodeFormats = null;
243 characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
245 source = Source.NONE;
246 decodeFormats = null;
248 if (lastResult == null) {
253 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
254 playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
256 // See if sound settings overrides this
257 AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
258 if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
262 vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
263 copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
267 private static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
268 List<String> scanFormats = null;
269 String scanFormatsString = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
270 if (scanFormatsString != null) {
271 scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));
273 return parseDecodeFormats(scanFormats, intent.getStringExtra(Intents.Scan.MODE));
276 private static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
277 List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
278 if (formats != null && formats.size() == 1 && formats.get(0) != null){
279 formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
281 return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
284 private static Vector<BarcodeFormat> parseDecodeFormats(List<String> scanFormats,
286 if (scanFormats != null) {
287 Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
289 for (String format : scanFormats) {
290 formats.add(BarcodeFormat.valueOf(format));
293 } catch (IllegalArgumentException iae) {
297 if (decodeMode != null) {
298 if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
299 return PRODUCT_FORMATS;
301 if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
302 return QR_CODE_FORMATS;
304 if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
305 return ONE_D_FORMATS;
312 protected void onPause() {
314 if (handler != null) {
315 handler.quitSynchronously();
318 CameraManager.get().closeDriver();
322 public boolean onKeyDown(int keyCode, KeyEvent event) {
323 if (keyCode == KeyEvent.KEYCODE_BACK) {
324 if (source == Source.NATIVE_APP_INTENT) {
325 setResult(RESULT_CANCELED);
328 } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
330 if (handler != null) {
331 handler.sendEmptyMessage(R.id.restart_preview);
335 } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
336 // Handle these events so they don't launch the Camera app
339 return super.onKeyDown(keyCode, event);
343 public boolean onCreateOptionsMenu(Menu menu) {
344 super.onCreateOptionsMenu(menu);
345 menu.add(0, SHARE_ID, 0, R.string.menu_share)
346 .setIcon(android.R.drawable.ic_menu_share);
347 menu.add(0, HISTORY_ID, 0, R.string.menu_history)
348 .setIcon(android.R.drawable.ic_menu_recent_history);
349 menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
350 .setIcon(android.R.drawable.ic_menu_preferences);
351 menu.add(0, HELP_ID, 0, R.string.menu_help)
352 .setIcon(android.R.drawable.ic_menu_help);
353 menu.add(0, ABOUT_ID, 0, R.string.menu_about)
354 .setIcon(android.R.drawable.ic_menu_info_details);
358 // Don't display the share menu item if the result overlay is showing.
360 public boolean onPrepareOptionsMenu(Menu menu) {
361 super.onPrepareOptionsMenu(menu);
362 menu.findItem(SHARE_ID).setVisible(lastResult == null);
367 public boolean onOptionsItemSelected(MenuItem item) {
368 switch (item.getItemId()) {
370 Intent intent = new Intent(Intent.ACTION_VIEW);
371 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
372 intent.setClassName(this, ShareActivity.class.getName());
373 startActivity(intent);
377 AlertDialog historyAlert = historyManager.buildAlert();
382 Intent intent = new Intent(Intent.ACTION_VIEW);
383 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
384 intent.setClassName(this, PreferencesActivity.class.getName());
385 startActivity(intent);
389 Intent intent = new Intent(Intent.ACTION_VIEW);
390 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
391 intent.setClassName(this, HelpActivity.class.getName());
392 startActivity(intent);
396 AlertDialog.Builder builder = new AlertDialog.Builder(this);
397 builder.setTitle(getString(R.string.title_about) + versionName);
398 builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
399 builder.setIcon(R.drawable.zxing_icon);
400 builder.setPositiveButton(R.string.button_open_browser, aboutListener);
401 builder.setNegativeButton(R.string.button_cancel, null);
405 return super.onOptionsItemSelected(item);
409 public void onConfigurationChanged(Configuration config) {
410 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
411 super.onConfigurationChanged(config);
414 public void surfaceCreated(SurfaceHolder holder) {
421 public void surfaceDestroyed(SurfaceHolder holder) {
425 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
430 * A valid barcode has been found, so give an indication of success and show the results.
432 * @param rawResult The contents of the barcode.
433 * @param barcode A greyscale bitmap of the camera data which was decoded.
435 public void handleDecode(Result rawResult, Bitmap barcode) {
436 lastResult = rawResult;
437 historyManager.addHistoryItem(rawResult);
438 if (barcode == null) {
439 // This is from history -- no saved barcode
440 handleDecodeInternally(rawResult, null);
442 playBeepSoundAndVibrate();
443 drawResultPoints(barcode, rawResult);
445 case NATIVE_APP_INTENT:
446 case PRODUCT_SEARCH_LINK:
447 handleDecodeExternally(rawResult, barcode);
450 if(returnUrlTemplate == null){
451 handleDecodeInternally(rawResult, barcode);
453 handleDecodeExternally(rawResult, barcode);
457 handleDecodeInternally(rawResult, barcode);
464 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
466 * @param barcode A bitmap of the captured image.
467 * @param rawResult The decoded results which contains the points to draw.
469 private void drawResultPoints(Bitmap barcode, Result rawResult) {
470 ResultPoint[] points = rawResult.getResultPoints();
471 if (points != null && points.length > 0) {
472 Canvas canvas = new Canvas(barcode);
473 Paint paint = new Paint();
474 paint.setColor(getResources().getColor(R.color.result_image_border));
475 paint.setStrokeWidth(3.0f);
476 paint.setStyle(Paint.Style.STROKE);
477 Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
478 canvas.drawRect(border, paint);
480 paint.setColor(getResources().getColor(R.color.result_points));
481 if (points.length == 2) {
482 paint.setStrokeWidth(4.0f);
483 canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
484 points[1].getY(), paint);
486 paint.setStrokeWidth(10.0f);
487 for (ResultPoint point : points) {
488 canvas.drawPoint(point.getX(), point.getY(), paint);
494 // Put up our own UI for how to handle the decoded contents.
495 private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
496 statusView.setVisibility(View.GONE);
497 viewfinderView.setVisibility(View.GONE);
498 resultView.setVisibility(View.VISIBLE);
500 ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
501 if (barcode == null) {
502 barcodeImageView.setImageResource(R.drawable.zxing_icon);
504 barcodeImageView.setImageBitmap(barcode);
506 barcodeImageView.setVisibility(View.VISIBLE);
508 TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
509 formatTextView.setVisibility(View.VISIBLE);
510 formatTextView.setText(getString(R.string.msg_default_format) + ": " +
511 rawResult.getBarcodeFormat().toString());
513 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
514 TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
515 typeTextView.setVisibility(View.VISIBLE);
516 typeTextView.setText(getString(R.string.msg_default_type) + ": " +
517 resultHandler.getType().toString());
519 DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
520 String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
521 TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
522 timeTextView.setVisibility(View.VISIBLE);
523 timeTextView.setText(getString(R.string.msg_default_time) + ": " + formattedTime);
525 TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
526 CharSequence title = getString(resultHandler.getDisplayTitle());
527 SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
528 styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
529 CharSequence displayContents = resultHandler.getDisplayContents();
530 styled.append(displayContents);
531 contentsTextView.setText(styled);
533 int buttonCount = resultHandler.getButtonCount();
534 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
535 buttonView.requestFocus();
536 for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
537 TextView button = (TextView) buttonView.getChildAt(x);
538 if (x < buttonCount) {
539 button.setVisibility(View.VISIBLE);
540 button.setText(resultHandler.getButtonText(x));
541 button.setOnClickListener(new ResultButtonListener(resultHandler, x));
543 button.setVisibility(View.GONE);
547 if (copyToClipboard) {
548 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
549 clipboard.setText(displayContents);
553 // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
554 private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
555 viewfinderView.drawResultBitmap(barcode);
557 // Since this message will only be shown for a second, just tell the user what kind of
558 // barcode was found (e.g. contact info) rather than the full contents, which they won't
559 // have time to read.
560 ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
561 TextView textView = (TextView) findViewById(R.id.status_text_view);
562 textView.setGravity(Gravity.CENTER);
563 textView.setTextSize(18.0f);
564 textView.setText(getString(resultHandler.getDisplayTitle()));
566 statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
568 if (copyToClipboard) {
569 ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
570 clipboard.setText(resultHandler.getDisplayContents());
573 if (source == Source.NATIVE_APP_INTENT) {
574 // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
575 // the deprecated intent is retired.
576 Intent intent = new Intent(getIntent().getAction());
577 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
578 intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
579 intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
580 Message message = Message.obtain(handler, R.id.return_scan_result);
581 message.obj = intent;
582 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
583 } else if (source == Source.PRODUCT_SEARCH_LINK) {
584 // Reformulate the URL which triggered us into a query, so that the request goes to the same
585 // TLD as the scan URL.
586 Message message = Message.obtain(handler, R.id.launch_product_query);
587 int end = sourceUrl.lastIndexOf("/scan");
588 message.obj = sourceUrl.substring(0, end) + "?q=" +
589 resultHandler.getDisplayContents().toString() + "&source=zxing";
590 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
591 } else if (source == Source.ZXING_LINK) {
592 // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate
593 // with the scanned code. This allows both queries and REST-style URLs to work.
594 Message message = Message.obtain(handler, R.id.launch_product_query);
595 message.obj = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER, resultHandler.getDisplayContents().toString());
596 handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
601 * We want the help screen to be shown automatically the first time a new version of the app is
602 * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
603 * it to a value stored as a preference.
605 private boolean showHelpOnFirstLaunch() {
607 PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
608 int currentVersion = info.versionCode;
609 // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
610 // version name here for display in the about box later.
611 this.versionName = info.versionName;
612 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
613 int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
614 if (currentVersion > lastVersion) {
615 prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
616 Intent intent = new Intent(this, HelpActivity.class);
617 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
618 // Show the default page on a clean install, and the what's new page on an upgrade.
619 String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
620 intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
621 startActivity(intent);
624 } catch (PackageManager.NameNotFoundException e) {
631 * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
634 private void initBeepSound() {
635 if (playBeep && mediaPlayer == null) {
636 // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
637 // so we now play on the music stream.
638 setVolumeControlStream(AudioManager.STREAM_MUSIC);
639 mediaPlayer = new MediaPlayer();
640 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
641 mediaPlayer.setOnCompletionListener(beepListener);
643 AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
645 mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
648 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
649 mediaPlayer.prepare();
650 } catch (IOException e) {
656 private void playBeepSoundAndVibrate() {
657 if (playBeep && mediaPlayer != null) {
661 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
662 vibrator.vibrate(VIBRATE_DURATION);
666 private void initCamera(SurfaceHolder surfaceHolder) {
668 CameraManager.get().openDriver(surfaceHolder);
669 } catch (IOException ioe) {
671 displayFrameworkBugMessageAndExit();
673 } catch (RuntimeException e) {
674 // Barcode Scanner has seen crashes in the wild of this variety:
675 // java.?lang.?RuntimeException: Fail to connect to camera service
676 Log.w(TAG, "Unexpected error initializating camera", e);
677 displayFrameworkBugMessageAndExit();
680 if (handler == null) {
681 boolean beginScanning = lastResult == null;
682 handler = new CaptureActivityHandler(this, decodeFormats, characterSet, beginScanning);
686 private void displayFrameworkBugMessageAndExit() {
687 AlertDialog.Builder builder = new AlertDialog.Builder(this);
688 builder.setTitle(getString(R.string.app_name));
689 builder.setMessage(getString(R.string.msg_camera_framework_bug));
690 builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
691 public void onClick(DialogInterface dialogInterface, int i) {
698 private void resetStatusView() {
699 resultView.setVisibility(View.GONE);
700 statusView.setVisibility(View.VISIBLE);
701 statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
702 viewfinderView.setVisibility(View.VISIBLE);
704 TextView textView = (TextView) findViewById(R.id.status_text_view);
705 textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
706 textView.setTextSize(14.0f);
707 textView.setText(R.string.msg_default_status);
711 public void drawViewfinder() {
712 viewfinderView.drawViewfinder();
716 * When the beep has finished playing, rewind to queue up another one.
718 private static class BeepListener implements OnCompletionListener {
719 public void onCompletion(MediaPlayer mediaPlayer) {
720 mediaPlayer.seekTo(0);