Did a bunch of renaming, there was no need for the Barcodes prefix.
[zxing.git] / android / src / com / google / zxing / client / android / CaptureActivity.java
1 /*
2  * Copyright (C) 2008 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.client.android;
18
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;
57
58 import java.io.IOException;
59
60 /**
61  * The barcode reader activity itself. This is loosely based on the CameraPreview
62  * example included in the Android SDK.
63  */
64 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
65
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;
70
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;
74
75   public CaptureActivityHandler mHandler;
76
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;
86
87   @Override
88   public void onCreate(Bundle icicle) {
89     super.onCreate(icicle);
90
91     Window window = getWindow();
92     window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
93     setContentView(R.layout.capture);
94
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);
99     mHandler = null;
100     mLastResult = null;
101     mHasSurface = false;
102   }
103
104   @Override
105   protected void onResume() {
106     super.onResume();
107
108     SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
109     SurfaceHolder surfaceHolder = surfaceView.getHolder();
110     if (mHasSurface) {
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);
114     } else {
115       // Install the callback and wait for surfaceCreated() to init the camera.
116       surfaceHolder.addCallback(this);
117       surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
118     }
119
120     Intent intent = getIntent();
121     if (intent != null && (intent.getAction().equals(Intents.Scan.ACTION) ||
122         intent.getAction().equals(Intents.Scan.DEPRECATED_ACTION))) {
123       mScanIntent = true;
124       mDecodeMode = intent.getStringExtra(Intents.Scan.MODE);
125       resetStatusView();
126     } else {
127       mScanIntent = false;
128       mDecodeMode = null;
129       if (mLastResult == null) {
130         resetStatusView();
131       }
132     }
133
134     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
135     mPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
136     initBeepSound();
137   }
138
139   @Override
140   protected void onPause() {
141     super.onPause();
142     if (mHandler != null) {
143       mHandler.quitSynchronously();
144       mHandler = null;
145     }
146     CameraManager.get().closeDriver();
147   }
148
149   @Override
150   public boolean onKeyDown(int keyCode, KeyEvent event) {
151     if (keyCode == KeyEvent.KEYCODE_BACK) {
152       if (mScanIntent) {
153         setResult(RESULT_CANCELED);
154         finish();
155         return true;
156       } else if (mLastResult != null) {
157         resetStatusView();
158         mHandler.sendEmptyMessage(R.id.restart_preview);
159         return true;
160       }
161     } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
162       // Handle these events so they don't launch the Camera app
163       return true;
164     }
165     return super.onKeyDown(keyCode, event);
166   }
167
168   @Override
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);
178     return true;
179   }
180
181   @Override
182   public boolean onOptionsItemSelected(MenuItem item) {
183     switch (item.getItemId()) {
184       case SHARE_ID: {
185         Intent intent = new Intent(Intent.ACTION_VIEW);
186         intent.setClassName(this, ShareActivity.class.getName());
187         startActivity(intent);
188         break;
189       }
190       case SETTINGS_ID: {
191         Intent intent = new Intent(Intent.ACTION_VIEW);
192         intent.setClassName(this, PreferencesActivity.class.getName());
193         startActivity(intent);
194         break;
195       }
196       case HELP_ID: {
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);
201         builder.show();
202         break;
203       }
204       case ABOUT_ID: {
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);
211         builder.show();
212         break;
213       }
214     }
215     return super.onOptionsItemSelected(item);
216   }
217
218   @Override
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);
222   }
223
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);
228     }
229   };
230
231   public void surfaceCreated(SurfaceHolder holder) {
232     if (!mHasSurface) {
233       mHasSurface = true;
234       initCamera(holder);
235     }
236   }
237
238   public void surfaceDestroyed(SurfaceHolder holder) {
239     mHasSurface = false;
240   }
241
242   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
243
244   }
245
246   /**
247    * A valid barcode has been found, so give an indication of success and show the results.
248    *
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.
252    */
253   public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
254     mLastResult = rawResult;
255     playBeepSound();
256     drawResultPoints(barcode, rawResult);
257
258     if (mScanIntent) {
259       handleDecodeForScanIntent(rawResult, barcode, duration);
260     } else {
261       mStatusView.setVisibility(View.GONE);
262       mViewfinderView.setVisibility(View.GONE);
263       mResultView.setVisibility(View.VISIBLE);
264
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);
269
270       TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
271       formatTextView.setText(getString(R.string.msg_default_format) + ": " +
272           rawResult.getBarcodeFormat().toString());
273
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());
278
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);
285
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));
295         } else {
296           button.setVisibility(View.GONE);
297         }
298       }
299     }
300   }
301
302   /**
303    * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
304    *
305    * @param barcode   A bitmap of the captured image.
306    * @param rawResult The decoded results which contains the points to draw.
307    */
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);
318
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);
324       } else {
325         paint.setStrokeWidth(10);
326         for (int x = 0; x < points.length; x++) {
327           canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
328         }
329       }
330     }
331   }
332
333   private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
334     mViewfinderView.drawResultBitmap(barcode);
335
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()));
344
345     mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
346
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);
355   }
356
357   /**
358    * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
359    * latency possible.
360    */
361   private void initBeepSound() {
362     if (mPlayBeep && mMediaPlayer == null) {
363       mMediaPlayer = new MediaPlayer();
364       mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
365       mMediaPlayer.setOnCompletionListener(mBeepListener);
366
367       AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
368       try {
369         mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
370             file.getLength());
371         file.close();
372         mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
373         mMediaPlayer.prepare();
374       } catch (IOException e) {
375         mMediaPlayer = null;
376       }
377     }
378   }
379
380   private void playBeepSound() {
381     if (mPlayBeep && mMediaPlayer != null) {
382       mMediaPlayer.start();
383     }
384   }
385
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);
391     }
392   }
393
394   /**
395    * When the beep has finished playing, rewind to queue up another one.
396    */
397   private final OnCompletionListener mBeepListener = new OnCompletionListener() {
398     public void onCompletion(MediaPlayer mediaPlayer) {
399       mediaPlayer.seekTo(0);
400     }
401   };
402
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);
408
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);
413     mLastResult = null;
414   }
415
416   public void drawViewfinder() {
417     mViewfinderView.drawViewfinder();
418   }
419
420 }