Hid the Share menu if the results screen was showing, since it didn't make sense...
[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   // Don't display the share menu item if the result overlay is showing.
182   @Override
183   public boolean onPrepareOptionsMenu(Menu menu) {
184     super.onPrepareOptionsMenu(menu);
185     menu.findItem(SHARE_ID).setVisible(mLastResult == null);
186     return true;
187   }
188
189   @Override
190   public boolean onOptionsItemSelected(MenuItem item) {
191     switch (item.getItemId()) {
192       case SHARE_ID: {
193         Intent intent = new Intent(Intent.ACTION_VIEW);
194         intent.setClassName(this, ShareActivity.class.getName());
195         startActivity(intent);
196         break;
197       }
198       case SETTINGS_ID: {
199         Intent intent = new Intent(Intent.ACTION_VIEW);
200         intent.setClassName(this, PreferencesActivity.class.getName());
201         startActivity(intent);
202         break;
203       }
204       case HELP_ID: {
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);
209         builder.show();
210         break;
211       }
212       case ABOUT_ID: {
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);
219         builder.show();
220         break;
221       }
222     }
223     return super.onOptionsItemSelected(item);
224   }
225
226   @Override
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);
230   }
231
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);
236     }
237   };
238
239   public void surfaceCreated(SurfaceHolder holder) {
240     if (!mHasSurface) {
241       mHasSurface = true;
242       initCamera(holder);
243     }
244   }
245
246   public void surfaceDestroyed(SurfaceHolder holder) {
247     mHasSurface = false;
248   }
249
250   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
251
252   }
253
254   /**
255    * A valid barcode has been found, so give an indication of success and show the results.
256    *
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.
260    */
261   public void handleDecode(Result rawResult, Bitmap barcode, int duration) {
262     mLastResult = rawResult;
263     playBeepSound();
264     drawResultPoints(barcode, rawResult);
265
266     if (mScanIntent) {
267       handleDecodeForScanIntent(rawResult, barcode, duration);
268     } else {
269       mStatusView.setVisibility(View.GONE);
270       mViewfinderView.setVisibility(View.GONE);
271       mResultView.setVisibility(View.VISIBLE);
272
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);
277
278       TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
279       formatTextView.setText(getString(R.string.msg_default_format) + ": " +
280           rawResult.getBarcodeFormat().toString());
281
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());
286
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);
293
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));
303         } else {
304           button.setVisibility(View.GONE);
305         }
306       }
307     }
308   }
309
310   /**
311    * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
312    *
313    * @param barcode   A bitmap of the captured image.
314    * @param rawResult The decoded results which contains the points to draw.
315    */
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);
326
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);
332       } else {
333         paint.setStrokeWidth(10);
334         for (int x = 0; x < points.length; x++) {
335           canvas.drawPoint(points[x].getX(), points[x].getY(), paint);
336         }
337       }
338     }
339   }
340
341   private void handleDecodeForScanIntent(Result rawResult, Bitmap barcode, int duration) {
342     mViewfinderView.drawResultBitmap(barcode);
343
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()));
352
353     mStatusView.setBackgroundColor(getResources().getColor(R.color.transparent));
354
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);
363   }
364
365   /**
366    * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
367    * latency possible.
368    */
369   private void initBeepSound() {
370     if (mPlayBeep && mMediaPlayer == null) {
371       mMediaPlayer = new MediaPlayer();
372       mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
373       mMediaPlayer.setOnCompletionListener(mBeepListener);
374
375       AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
376       try {
377         mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
378             file.getLength());
379         file.close();
380         mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
381         mMediaPlayer.prepare();
382       } catch (IOException e) {
383         mMediaPlayer = null;
384       }
385     }
386   }
387
388   private void playBeepSound() {
389     if (mPlayBeep && mMediaPlayer != null) {
390       mMediaPlayer.start();
391     }
392   }
393
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);
399     }
400   }
401
402   /**
403    * When the beep has finished playing, rewind to queue up another one.
404    */
405   private final OnCompletionListener mBeepListener = new OnCompletionListener() {
406     public void onCompletion(MediaPlayer mediaPlayer) {
407       mediaPlayer.seekTo(0);
408     }
409   };
410
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);
416
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);
421     mLastResult = null;
422   }
423
424   public void drawViewfinder() {
425     mViewfinderView.drawViewfinder();
426   }
427
428 }