• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
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.android.camera;
18 
19 import android.app.Activity;
20 import android.content.ActivityNotFoundException;
21 import android.content.BroadcastReceiver;
22 import android.content.ContentProviderClient;
23 import android.content.ContentResolver;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.IntentFilter;
27 import android.content.SharedPreferences;
28 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
29 import android.content.res.Resources;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.hardware.Camera.Parameters;
33 import android.hardware.Camera.PictureCallback;
34 import android.hardware.Camera.Size;
35 import android.location.Location;
36 import android.location.LocationManager;
37 import android.location.LocationProvider;
38 import android.media.AudioManager;
39 import android.media.ToneGenerator;
40 import android.net.Uri;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.os.Debug;
44 import android.os.Environment;
45 import android.os.Handler;
46 import android.os.Message;
47 import android.os.SystemClock;
48 import android.os.SystemProperties;
49 import android.preference.PreferenceManager;
50 import android.provider.MediaStore;
51 import android.text.format.DateFormat;
52 import android.util.AttributeSet;
53 import android.util.Log;
54 import android.view.Display;
55 import android.view.GestureDetector;
56 import android.view.KeyEvent;
57 import android.view.LayoutInflater;
58 import android.view.Menu;
59 import android.view.MenuItem;
60 import android.view.MotionEvent;
61 import android.view.OrientationEventListener;
62 import android.view.SurfaceHolder;
63 import android.view.SurfaceView;
64 import android.view.View;
65 import android.view.ViewGroup;
66 import android.view.Window;
67 import android.view.WindowManager;
68 import android.view.MenuItem.OnMenuItemClickListener;
69 import android.widget.ImageView;
70 import android.widget.ZoomButtonsController;
71 
72 import com.android.camera.gallery.IImage;
73 import com.android.camera.gallery.IImageList;
74 
75 import java.io.File;
76 import java.io.FileNotFoundException;
77 import java.io.FileOutputStream;
78 import java.io.IOException;
79 import java.io.OutputStream;
80 import java.util.ArrayList;
81 import java.util.Collections;
82 import java.util.List;
83 
84 /**
85  * Activity of the Camera which used to see preview and take pictures.
86  */
87 public class Camera extends Activity implements View.OnClickListener,
88         ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
89         Switcher.OnSwitchListener, OnScreenSettings.OnVisibilityChangedListener,
90         OnSharedPreferenceChangeListener {
91 
92     private static final String TAG = "camera";
93 
94     private static final int CROP_MSG = 1;
95     private static final int FIRST_TIME_INIT = 2;
96     private static final int RESTART_PREVIEW = 3;
97     private static final int CLEAR_SCREEN_DELAY = 4;
98 
99     private static final String GPS_MODE_ON = "on";
100     private static final String GPS_MODE_OFF = "off";
101 
102     private static final int SCREEN_DELAY = 2 * 60 * 1000;
103     private static final int FOCUS_BEEP_VOLUME = 100;
104 
105     private static final String SCENE_MODE_ON = "on";
106     private static final String SCENE_MODE_OFF = "off";
107 
108     private boolean mZooming = false;
109     private boolean mSmoothZoomSupported = false;
110     private int mZoomValue;  // The current zoom value.
111     private int mZoomMax;
112 
113     private Parameters mParameters;
114     private Parameters mInitialParams;
115 
116     private OrientationEventListener mOrientationListener;
117     private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
118     private SharedPreferences mPreferences;
119 
120     private static final int IDLE = 1;
121     private static final int SNAPSHOT_IN_PROGRESS = 2;
122 
123     private static final boolean SWITCH_CAMERA = true;
124     private static final boolean SWITCH_VIDEO = false;
125 
126     private int mStatus = IDLE;
127     private static final String sTempCropFilename = "crop-temp";
128 
129     private android.hardware.Camera mCameraDevice;
130     private ContentProviderClient mMediaProviderClient;
131     private SurfaceView mSurfaceView;
132     private SurfaceHolder mSurfaceHolder = null;
133     private ShutterButton mShutterButton;
134     private FocusRectangle mFocusRectangle;
135     private IconIndicator mGpsIndicator;
136     private IconIndicator mFlashIndicator;
137     private IconIndicator mFocusIndicator;
138     private IconIndicator mWhitebalanceIndicator;
139     private IconIndicator mSceneModeIndicator;
140     private ToneGenerator mFocusToneGenerator;
141     private ZoomButtonsController mZoomButtons;
142     private GestureDetector mGestureDetector;
143     private Switcher mSwitcher;
144     private boolean mStartPreviewFail = false;
145 
146     // mPostCaptureAlert, mLastPictureButton, mThumbController
147     // are non-null only if isImageCaptureIntent() is true.
148     private ImageView mLastPictureButton;
149     private ThumbnailController mThumbController;
150 
151     // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
152     private String mCropValue;
153     private Uri mSaveUri;
154 
155     private ImageCapture mImageCapture = null;
156 
157     private boolean mPreviewing;
158     private boolean mPausing;
159     private boolean mFirstTimeInitialized;
160     private boolean mIsImageCaptureIntent;
161     private boolean mRecordLocation;
162 
163     private static final int FOCUS_NOT_STARTED = 0;
164     private static final int FOCUSING = 1;
165     private static final int FOCUSING_SNAP_ON_FINISH = 2;
166     private static final int FOCUS_SUCCESS = 3;
167     private static final int FOCUS_FAIL = 4;
168     private int mFocusState = FOCUS_NOT_STARTED;
169 
170     private ContentResolver mContentResolver;
171     private boolean mDidRegister = false;
172 
173     private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
174 
175     private LocationManager mLocationManager = null;
176 
177     // Use OneShotPreviewCallback to measure the time between
178     // JpegPictureCallback and preview.
179     private final OneShotPreviewCallback mOneShotPreviewCallback =
180             new OneShotPreviewCallback();
181     private final ShutterCallback mShutterCallback = new ShutterCallback();
182     private final PostViewPictureCallback mPostViewPictureCallback =
183             new PostViewPictureCallback();
184     private final RawPictureCallback mRawPictureCallback =
185             new RawPictureCallback();
186     private final AutoFocusCallback mAutoFocusCallback =
187             new AutoFocusCallback();
188     private final ZoomCallback mZoomCallback = new ZoomCallback();
189     // Use the ErrorCallback to capture the crash count
190     // on the mediaserver
191     private final ErrorCallback mErrorCallback = new ErrorCallback();
192 
193     private long mFocusStartTime;
194     private long mFocusCallbackTime;
195     private long mCaptureStartTime;
196     private long mShutterCallbackTime;
197     private long mPostViewPictureCallbackTime;
198     private long mRawPictureCallbackTime;
199     private long mJpegPictureCallbackTime;
200     private int mPicturesRemaining;
201 
202     // These latency time are for the CameraLatency test.
203     public long mAutoFocusTime;
204     public long mShutterLag;
205     public long mShutterToPictureDisplayedTime;
206     public long mPictureDisplayedToJpegCallbackTime;
207     public long mJpegCallbackToFirstFrameTime;
208 
209     // Add the media server tag
210     public static boolean mMediaServerDied = false;
211     // Focus mode. Options are pref_camera_focusmode_entryvalues.
212     private String mFocusMode;
213 
214     private final Handler mHandler = new MainHandler();
215     private OnScreenSettings mSettings;
216 
217     /**
218      * This Handler is used to post message back onto the main thread of the
219      * application
220      */
221     private class MainHandler extends Handler {
222         @Override
handleMessage(Message msg)223         public void handleMessage(Message msg) {
224             switch (msg.what) {
225                 case RESTART_PREVIEW: {
226                     restartPreview();
227                     break;
228                 }
229 
230                 case CLEAR_SCREEN_DELAY: {
231                     getWindow().clearFlags(
232                             WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
233                     break;
234                 }
235 
236                 case FIRST_TIME_INIT: {
237                     initializeFirstTime();
238                     break;
239                 }
240             }
241         }
242     }
243 
keepMediaProviderInstance()244     private void keepMediaProviderInstance() {
245         // We want to keep a reference to MediaProvider in camera's lifecycle.
246         // TODO: Utilize mMediaProviderClient instance to replace
247         // ContentResolver calls.
248         if (mMediaProviderClient == null) {
249             mMediaProviderClient = getContentResolver()
250                     .acquireContentProviderClient(MediaStore.AUTHORITY);
251         }
252     }
253 
254     // Snapshots can only be taken after this is called. It should be called
255     // once only. We could have done these things in onCreate() but we want to
256     // make preview screen appear as soon as possible.
initializeFirstTime()257     private void initializeFirstTime() {
258         if (mFirstTimeInitialized) return;
259 
260         // Create orientation listenter. This should be done first because it
261         // takes some time to get first orientation.
262         mOrientationListener =
263                 new OrientationEventListener(Camera.this) {
264             @Override
265             public void onOrientationChanged(int orientation) {
266                 // We keep the last known orientation. So if the user
267                 // first orient the camera then point the camera to
268                 // floor/sky, we still have the correct orientation.
269                 if (orientation != ORIENTATION_UNKNOWN) {
270                     mLastOrientation = orientation;
271                 }
272             }
273         };
274         mOrientationListener.enable();
275 
276         // Initialize location sevice.
277         mLocationManager = (LocationManager)
278                 getSystemService(Context.LOCATION_SERVICE);
279         readPreference();
280         if (mRecordLocation) startReceivingLocationUpdates();
281 
282         keepMediaProviderInstance();
283         checkStorage();
284 
285         // Initialize last picture button.
286         mContentResolver = getContentResolver();
287         if (!mIsImageCaptureIntent)  {
288             findViewById(R.id.camera_switch).setOnClickListener(this);
289             mLastPictureButton =
290                     (ImageView) findViewById(R.id.review_thumbnail);
291             mLastPictureButton.setOnClickListener(this);
292             mThumbController = new ThumbnailController(
293                     getResources(), mLastPictureButton, mContentResolver);
294             mThumbController.loadData(ImageManager.getLastImageThumbPath());
295             // Update last image thumbnail.
296             updateThumbnailButton();
297         }
298 
299         // Initialize shutter button.
300         mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
301         mShutterButton.setOnShutterButtonListener(this);
302         mShutterButton.setVisibility(View.VISIBLE);
303 
304         mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
305         updateFocusIndicator();
306 
307         // Initialize GPS indicator.
308         mGpsIndicator = (IconIndicator) findViewById(R.id.gps_icon);
309 
310         ImageManager.ensureOSXCompatibleFolder();
311 
312         installIntentFilter();
313 
314         initializeFocusTone();
315 
316         initializeZoom();
317 
318         mFirstTimeInitialized = true;
319     }
320 
updateThumbnailButton()321     private void updateThumbnailButton() {
322         // Update last image if URI is invalid and the storage is ready.
323         if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) {
324             updateLastImage();
325         }
326         mThumbController.updateDisplayIfNeeded();
327     }
328 
329     // If the activity is paused and resumed, this method will be called in
330     // onResume.
initializeSecondTime()331     private void initializeSecondTime() {
332         // Start orientation listener as soon as possible because it takes
333         // some time to get first orientation.
334         mOrientationListener.enable();
335 
336         // Start location update if needed.
337         readPreference();
338         if (mRecordLocation) startReceivingLocationUpdates();
339 
340         installIntentFilter();
341 
342         initializeFocusTone();
343 
344         keepMediaProviderInstance();
345         checkStorage();
346 
347         if (mZoomButtons != null) {
348             mCameraDevice.setZoomCallback(mZoomCallback);
349         }
350 
351         if (!mIsImageCaptureIntent) {
352             updateThumbnailButton();
353         }
354     }
355 
initializeZoom()356     private void initializeZoom() {
357         if (!mParameters.isZoomSupported()) return;
358 
359         mZoomMax = mParameters.getMaxZoom();
360         Log.v(TAG, "Max zoom=" + mZoomMax);
361         mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
362         Log.v(TAG, "Smooth zoom supported=" + mSmoothZoomSupported);
363 
364         mGestureDetector = new GestureDetector(this, new ZoomGestureListener());
365         mCameraDevice.setZoomCallback(mZoomCallback);
366         mZoomButtons = new ZoomButtonsController(mSurfaceView);
367         mZoomButtons.setAutoDismissed(true);
368         mZoomButtons.setZoomSpeed(100);
369         mZoomButtons.setOnZoomListener(
370                 new ZoomButtonsController.OnZoomListener() {
371             public void onVisibilityChanged(boolean visible) {
372                 if (visible) {
373                     updateZoomButtonsEnabled();
374                 }
375             }
376 
377             public void onZoom(boolean zoomIn) {
378                 if (isZooming()) return;
379 
380                 if (zoomIn) {
381                     if (mZoomValue < mZoomMax) {
382                         if (mSmoothZoomSupported) {
383                             mCameraDevice.startSmoothZoom(mZoomValue + 1);
384                             mZooming = true;
385                         } else {
386                             mParameters.setZoom(++mZoomValue);
387                             mCameraDevice.setParameters(mParameters);
388                             updateZoomButtonsEnabled();
389                         }
390                     }
391                 } else {
392                     if (mZoomValue > 0) {
393                         if (mSmoothZoomSupported) {
394                             mCameraDevice.startSmoothZoom(mZoomValue - 1);
395                             mZooming = true;
396                         } else {
397                             mParameters.setZoom(--mZoomValue);
398                             mCameraDevice.setParameters(mParameters);
399                             updateZoomButtonsEnabled();
400                         }
401                     }
402                 }
403             }
404         });
405     }
406 
onVisibilityChanged(boolean visible)407     public void onVisibilityChanged(boolean visible) {
408         // When the on-screen setting is not displayed, we show the gripper.
409         // When the on-screen setting is displayed, we hide the gripper.
410         int reverseVisibility = visible ? View.INVISIBLE : View.VISIBLE;
411         findViewById(R.id.btn_gripper).setVisibility(reverseVisibility);
412         findViewById(R.id.indicator_bar).setVisibility(reverseVisibility);
413 
414         if (visible) {
415             mPreferences.registerOnSharedPreferenceChangeListener(this);
416         } else {
417             mPreferences.unregisterOnSharedPreferenceChangeListener(this);
418         }
419     }
420 
isZooming()421     private boolean isZooming() {
422         Log.v(TAG, "mZooming=" + mZooming);
423         return mZooming;
424     }
425 
updateZoomButtonsEnabled()426     private void updateZoomButtonsEnabled() {
427         mZoomButtons.setZoomInEnabled(mZoomValue < mZoomMax);
428         mZoomButtons.setZoomOutEnabled(mZoomValue > 0);
429     }
430 
431     private class ZoomGestureListener extends
432             GestureDetector.SimpleOnGestureListener {
433         @Override
onDown(MotionEvent e)434         public boolean onDown(MotionEvent e) {
435             // Show zoom buttons only when preview is started and snapshot
436             // is not in progress. mZoomButtons may be null if it is not
437             // initialized.
438             if (!mPausing && isCameraIdle() && mPreviewing
439                     && mZoomButtons != null) {
440                 mZoomButtons.setVisible(true);
441             }
442             return true;
443         }
444 
445         @Override
onDoubleTap(MotionEvent e)446         public boolean onDoubleTap(MotionEvent e) {
447             // Perform zoom only when preview is started and snapshot is not in
448             // progress.
449             if (mPausing || !isCameraIdle() || !mPreviewing
450                     || mZoomButtons == null || isZooming()) {
451                 return false;
452             }
453 
454             if (mZoomValue < mZoomMax) {
455                 // Zoom in to the maximum.
456                 while (mZoomValue < mZoomMax) {
457                     mParameters.setZoom(++mZoomValue);
458                     mCameraDevice.setParameters(mParameters);
459                     // Wait for a while so we are not changing zoom too fast.
460                     try {
461                         Thread.sleep(5);
462                     } catch (InterruptedException ex) {
463                     }
464                 }
465             } else {
466                 // Zoom out to the minimum.
467                 while (mZoomValue > 0) {
468                     mParameters.setZoom(--mZoomValue);
469                     mCameraDevice.setParameters(mParameters);
470                     // Wait for a while so we are not changing zoom too fast.
471                     try {
472                         Thread.sleep(5);
473                     } catch (InterruptedException ex) {
474                     }
475                 }
476             }
477             updateZoomButtonsEnabled();
478             return true;
479         }
480     }
481 
482     @Override
dispatchTouchEvent(MotionEvent m)483     public boolean dispatchTouchEvent(MotionEvent m) {
484         if (!super.dispatchTouchEvent(m) && mGestureDetector != null) {
485             return mGestureDetector.onTouchEvent(m);
486         }
487         return true;
488     }
489 
490     LocationListener [] mLocationListeners = new LocationListener[] {
491             new LocationListener(LocationManager.GPS_PROVIDER),
492             new LocationListener(LocationManager.NETWORK_PROVIDER)
493     };
494 
495     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
496         @Override
497         public void onReceive(Context context, Intent intent) {
498             String action = intent.getAction();
499             if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
500                     || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
501                     || action.equals(Intent.ACTION_MEDIA_CHECKING)
502                     || action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
503                 checkStorage();
504             } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
505                 checkStorage();
506                 if (!mIsImageCaptureIntent)  {
507                     updateThumbnailButton();
508                 }
509             }
510         }
511     };
512 
513     private class LocationListener
514             implements android.location.LocationListener {
515         Location mLastLocation;
516         boolean mValid = false;
517         String mProvider;
518 
LocationListener(String provider)519         public LocationListener(String provider) {
520             mProvider = provider;
521             mLastLocation = new Location(mProvider);
522         }
523 
onLocationChanged(Location newLocation)524         public void onLocationChanged(Location newLocation) {
525             if (newLocation.getLatitude() == 0.0
526                     && newLocation.getLongitude() == 0.0) {
527                 // Hack to filter out 0.0,0.0 locations
528                 return;
529             }
530             // If GPS is available before start camera, we won't get status
531             // update so update GPS indicator when we receive data.
532             if (mRecordLocation
533                     && LocationManager.GPS_PROVIDER.equals(mProvider)) {
534                 mGpsIndicator.setMode(GPS_MODE_ON);
535             }
536             mLastLocation.set(newLocation);
537             mValid = true;
538         }
539 
onProviderEnabled(String provider)540         public void onProviderEnabled(String provider) {
541         }
542 
onProviderDisabled(String provider)543         public void onProviderDisabled(String provider) {
544             mValid = false;
545         }
546 
onStatusChanged( String provider, int status, Bundle extras)547         public void onStatusChanged(
548                 String provider, int status, Bundle extras) {
549             switch(status) {
550                 case LocationProvider.OUT_OF_SERVICE:
551                 case LocationProvider.TEMPORARILY_UNAVAILABLE: {
552                     mValid = false;
553                     if (mRecordLocation &&
554                             LocationManager.GPS_PROVIDER.equals(provider)) {
555                         mGpsIndicator.setMode(GPS_MODE_OFF);
556                     }
557                     break;
558                 }
559             }
560         }
561 
current()562         public Location current() {
563             return mValid ? mLastLocation : null;
564         }
565     }
566 
567     private final class OneShotPreviewCallback
568             implements android.hardware.Camera.PreviewCallback {
onPreviewFrame(byte[] data, android.hardware.Camera camera)569         public void onPreviewFrame(byte[] data,
570                                    android.hardware.Camera camera) {
571             long now = System.currentTimeMillis();
572             if (mJpegPictureCallbackTime != 0) {
573                 mJpegCallbackToFirstFrameTime = now - mJpegPictureCallbackTime;
574                 Log.v(TAG, "mJpegCallbackToFirstFrameTime = "
575                         + mJpegCallbackToFirstFrameTime + "ms");
576                 mJpegPictureCallbackTime = 0;
577             } else {
578                 Log.v(TAG, "Got first frame");
579             }
580         }
581     }
582 
583     private final class ShutterCallback
584             implements android.hardware.Camera.ShutterCallback {
onShutter()585         public void onShutter() {
586             mShutterCallbackTime = System.currentTimeMillis();
587             mShutterLag = mShutterCallbackTime - mCaptureStartTime;
588             Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
589             clearFocusState();
590         }
591     }
592 
593     private final class PostViewPictureCallback implements PictureCallback {
onPictureTaken( byte [] data, android.hardware.Camera camera)594         public void onPictureTaken(
595                 byte [] data, android.hardware.Camera camera) {
596             mPostViewPictureCallbackTime = System.currentTimeMillis();
597             Log.v(TAG, "mShutterToPostViewCallbackTime = "
598                     + (mPostViewPictureCallbackTime - mShutterCallbackTime)
599                     + "ms");
600         }
601     }
602 
603     private final class RawPictureCallback implements PictureCallback {
onPictureTaken( byte [] rawData, android.hardware.Camera camera)604         public void onPictureTaken(
605                 byte [] rawData, android.hardware.Camera camera) {
606             mRawPictureCallbackTime = System.currentTimeMillis();
607             Log.v(TAG, "mShutterToRawCallbackTime = "
608                     + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
609         }
610     }
611 
612     private final class JpegPictureCallback implements PictureCallback {
613         Location mLocation;
614 
JpegPictureCallback(Location loc)615         public JpegPictureCallback(Location loc) {
616             mLocation = loc;
617         }
618 
onPictureTaken( final byte [] jpegData, final android.hardware.Camera camera)619         public void onPictureTaken(
620                 final byte [] jpegData, final android.hardware.Camera camera) {
621             if (mPausing) {
622                 return;
623             }
624 
625             mJpegPictureCallbackTime = System.currentTimeMillis();
626             // If postview callback has arrived, the captured image is displayed
627             // in postview callback. If not, the captured image is displayed in
628             // raw picture callback.
629             if (mPostViewPictureCallbackTime != 0) {
630                 mShutterToPictureDisplayedTime =
631                         mPostViewPictureCallbackTime - mShutterCallbackTime;
632                 mPictureDisplayedToJpegCallbackTime =
633                         mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
634             } else {
635                 mShutterToPictureDisplayedTime =
636                         mRawPictureCallbackTime - mShutterCallbackTime;
637                 mPictureDisplayedToJpegCallbackTime =
638                         mJpegPictureCallbackTime - mRawPictureCallbackTime;
639             }
640             Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
641                     + mPictureDisplayedToJpegCallbackTime + "ms");
642 
643             if (!mIsImageCaptureIntent) {
644                 // We want to show the taken picture for a while, so we wait
645                 // for at least 1.2 second before restarting the preview.
646                 long delay = 1200 - mPictureDisplayedToJpegCallbackTime;
647                 if (delay < 0) {
648                     restartPreview();
649                 } else {
650                     mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
651                 }
652             }
653             mImageCapture.storeImage(jpegData, camera, mLocation);
654 
655             // Calculate this in advance of each shot so we don't add to shutter
656             // latency. It's true that someone else could write to the SD card in
657             // the mean time and fill it, but that could have happened between the
658             // shutter press and saving the JPEG too.
659             calculatePicturesRemaining();
660         }
661     }
662 
663     private final class AutoFocusCallback
664             implements android.hardware.Camera.AutoFocusCallback {
onAutoFocus( boolean focused, android.hardware.Camera camera)665         public void onAutoFocus(
666                 boolean focused, android.hardware.Camera camera) {
667             mFocusCallbackTime = System.currentTimeMillis();
668             mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
669             Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
670             if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
671                 // Take the picture no matter focus succeeds or fails. No need
672                 // to play the AF sound if we're about to play the shutter
673                 // sound.
674                 if (focused) {
675                     mFocusState = FOCUS_SUCCESS;
676                 } else {
677                     mFocusState = FOCUS_FAIL;
678                 }
679                 mImageCapture.onSnap();
680             } else if (mFocusState == FOCUSING) {
681                 // User is half-pressing the focus key. Play the focus tone.
682                 // Do not take the picture now.
683                 ToneGenerator tg = mFocusToneGenerator;
684                 if (tg != null) {
685                     tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
686                 }
687                 if (focused) {
688                     mFocusState = FOCUS_SUCCESS;
689                 } else {
690                     mFocusState = FOCUS_FAIL;
691                 }
692             } else if (mFocusState == FOCUS_NOT_STARTED) {
693                 // User has released the focus key before focus completes.
694                 // Do nothing.
695             }
696             updateFocusIndicator();
697         }
698     }
699 
700     private final class ErrorCallback
701         implements android.hardware.Camera.ErrorCallback {
onError(int error, android.hardware.Camera camera)702         public void onError(int error, android.hardware.Camera camera) {
703             if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
704                  mMediaServerDied = true;
705                  Log.v(TAG, "media server died");
706             }
707         }
708     }
709 
710     private final class ZoomCallback
711             implements android.hardware.Camera.ZoomCallback {
onZoomUpdate(int zoomValue, boolean stopped, android.hardware.Camera camera)712         public void onZoomUpdate(int zoomValue, boolean stopped,
713                                  android.hardware.Camera camera) {
714             Log.v(TAG, "ZoomCallback: zoom value=" + zoomValue + ". stopped="
715                     + stopped);
716             mZoomValue = zoomValue;
717             // Keep mParameters up to date. We do not getParameter again in
718             // takePicture. If we do not do this, wrong zoom value will be set.
719             mParameters.setZoom(zoomValue);
720             // We only care if the zoom is stopped. mZooming is set to true when
721             // we start smooth zoom.
722             if (stopped) mZooming = false;
723             updateZoomButtonsEnabled();
724         }
725     }
726 
727     private class ImageCapture {
728 
729         private boolean mCancel = false;
730 
731         private Uri mLastContentUri;
732 
733         byte[] mCaptureOnlyData;
734 
735         // Returns the rotation degree in the jpeg header.
storeImage(byte[] data, Location loc)736         private int storeImage(byte[] data, Location loc) {
737             try {
738                 long dateTaken = System.currentTimeMillis();
739                 String name = createName(dateTaken) + ".jpg";
740                 int[] degree = new int[1];
741                 mLastContentUri = ImageManager.addImage(
742                         mContentResolver,
743                         name,
744                         dateTaken,
745                         loc, // location from gps/network
746                         ImageManager.CAMERA_IMAGE_BUCKET_NAME, name,
747                         null, data,
748                         degree);
749                 if (mLastContentUri == null) {
750                     // this means we got an error
751                     mCancel = true;
752                 }
753                 if (!mCancel) {
754                     ImageManager.setImageSize(mContentResolver, mLastContentUri,
755                             new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME,
756                             name).length());
757                 }
758                 return degree[0];
759             } catch (Exception ex) {
760                 Log.e(TAG, "Exception while compressing image.", ex);
761                 return 0;
762             }
763         }
764 
storeImage(final byte[] data, android.hardware.Camera camera, Location loc)765         public void storeImage(final byte[] data,
766                 android.hardware.Camera camera, Location loc) {
767             if (!mIsImageCaptureIntent) {
768                 int degree = storeImage(data, loc);
769                 sendBroadcast(new Intent(
770                         "com.android.camera.NEW_PICTURE", mLastContentUri));
771                 setLastPictureThumb(data, degree,
772                         mImageCapture.getLastCaptureUri());
773                 mThumbController.updateDisplayIfNeeded();
774             } else {
775                 mCaptureOnlyData = data;
776                 showPostCaptureAlert();
777             }
778         }
779 
780         /**
781          * Initiate the capture of an image.
782          */
initiate()783         public void initiate() {
784             if (mCameraDevice == null) {
785                 return;
786             }
787 
788             mCancel = false;
789 
790             capture();
791         }
792 
getLastCaptureUri()793         public Uri getLastCaptureUri() {
794             return mLastContentUri;
795         }
796 
getLastCaptureData()797         public byte[] getLastCaptureData() {
798             return mCaptureOnlyData;
799         }
800 
capture()801         private void capture() {
802             mCaptureOnlyData = null;
803 
804             // Set rotation.
805             int orientation = mLastOrientation;
806             if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
807                 orientation += 90;
808             }
809             orientation = ImageManager.roundOrientation(orientation);
810             Log.v(TAG, "mLastOrientation = " + mLastOrientation
811                     + ", orientation = " + orientation);
812             mParameters.setRotation(orientation);
813 
814             // Clear previous GPS location from the parameters.
815             mParameters.removeGpsData();
816 
817             // Set GPS location.
818             Location loc = mRecordLocation ? getCurrentLocation() : null;
819             if (loc != null) {
820                 double lat = loc.getLatitude();
821                 double lon = loc.getLongitude();
822                 boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
823 
824                 if (hasLatLon) {
825                     mParameters.setGpsLatitude(lat);
826                     mParameters.setGpsLongitude(lon);
827                     if (loc.hasAltitude()) {
828                         mParameters.setGpsAltitude(loc.getAltitude());
829                     } else {
830                         // for NETWORK_PROVIDER location provider, we may have
831                         // no altitude information, but the driver needs it, so
832                         // we fake one.
833                         mParameters.setGpsAltitude(0);
834                     }
835                     if (loc.getTime() != 0) {
836                         // Location.getTime() is UTC in milliseconds.
837                         // gps-timestamp is UTC in seconds.
838                         long utcTimeSeconds = loc.getTime() / 1000;
839                         mParameters.setGpsTimestamp(utcTimeSeconds);
840                     }
841                 } else {
842                     loc = null;
843                 }
844             }
845 
846             mCameraDevice.setParameters(mParameters);
847 
848             mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
849                     mPostViewPictureCallback, new JpegPictureCallback(loc));
850             mPreviewing = false;
851         }
852 
onSnap()853         public void onSnap() {
854             // If we are already in the middle of taking a snapshot then ignore.
855             if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
856                 return;
857             }
858             mCaptureStartTime = System.currentTimeMillis();
859             mPostViewPictureCallbackTime = 0;
860 
861             // Don't check the filesystem here, we can't afford the latency.
862             // Instead, check the cached value which was calculated when the
863             // preview was restarted.
864             if (mPicturesRemaining < 1) {
865                 updateStorageHint(mPicturesRemaining);
866                 return;
867             }
868 
869             mStatus = SNAPSHOT_IN_PROGRESS;
870 
871             mImageCapture.initiate();
872         }
873 
clearLastData()874         private void clearLastData() {
875             mCaptureOnlyData = null;
876         }
877     }
878 
saveDataToFile(String filePath, byte[] data)879     public boolean saveDataToFile(String filePath, byte[] data) {
880         FileOutputStream f = null;
881         try {
882             f = new FileOutputStream(filePath);
883             f.write(data);
884         } catch (IOException e) {
885             return false;
886         } finally {
887             MenuHelper.closeSilently(f);
888         }
889         return true;
890     }
891 
setLastPictureThumb(byte[] data, int degree, Uri uri)892     private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
893         BitmapFactory.Options options = new BitmapFactory.Options();
894         options.inSampleSize = 16;
895         Bitmap lastPictureThumb =
896                 BitmapFactory.decodeByteArray(data, 0, data.length, options);
897         lastPictureThumb = Util.rotate(lastPictureThumb, degree);
898         mThumbController.setData(uri, lastPictureThumb);
899     }
900 
createName(long dateTaken)901     private static String createName(long dateTaken) {
902         return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString();
903     }
904 
905     @Override
onCreate(Bundle icicle)906     public void onCreate(Bundle icicle) {
907         super.onCreate(icicle);
908 
909         Window win = getWindow();
910         win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
911         setContentView(R.layout.camera);
912         mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview);
913 
914         mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
915         CameraSettings.upgradePreferences(mPreferences);
916 
917         /*
918          * To reduce startup time, we start the preview in another thread.
919          * We make sure the preview is started at the end of onCreate.
920          */
921         Thread startPreviewThread = new Thread(new Runnable() {
922             public void run() {
923                 try {
924                     mStartPreviewFail = false;
925                     startPreview();
926                 } catch (CameraHardwareException e) {
927                     // In eng build, we throw the exception so that test tool
928                     // can detect it and report it
929                     if ("eng".equals(Build.TYPE)) {
930                         throw new RuntimeException(e);
931                     }
932                     mStartPreviewFail = true;
933                 }
934             }
935         });
936         startPreviewThread.start();
937 
938         // don't set mSurfaceHolder here. We have it set ONLY within
939         // surfaceChanged / surfaceDestroyed, other parts of the code
940         // assume that when it is set, the surface is also set.
941         SurfaceHolder holder = mSurfaceView.getHolder();
942         holder.addCallback(this);
943         holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
944 
945         mIsImageCaptureIntent = isImageCaptureIntent();
946         if (mIsImageCaptureIntent) {
947             setupCaptureParams();
948         }
949 
950         LayoutInflater inflater = getLayoutInflater();
951 
952         ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
953         if (mIsImageCaptureIntent) {
954             View controlBar = inflater.inflate(
955                     R.layout.attach_camera_control, rootView);
956             controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
957             controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
958             controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
959         } else {
960             inflater.inflate(R.layout.camera_control, rootView);
961             mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
962             mSwitcher.setOnSwitchListener(this);
963             mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
964         }
965         findViewById(R.id.btn_gripper)
966                 .setOnTouchListener(new GripperTouchListener());
967 
968         mFlashIndicator = (IconIndicator) findViewById(R.id.flash_icon);
969         mFocusIndicator = (IconIndicator) findViewById(R.id.focus_icon);
970         mSceneModeIndicator = (IconIndicator) findViewById(R.id.scenemode_icon);
971         mWhitebalanceIndicator =
972                 (IconIndicator) findViewById(R.id.whitebalance_icon);
973 
974         // Make sure preview is started.
975         try {
976             startPreviewThread.join();
977             if (mStartPreviewFail) {
978                 showCameraErrorAndFinish();
979                 return;
980             }
981         } catch (InterruptedException ex) {
982             // ignore
983         }
984     }
985 
986     private class GripperTouchListener implements View.OnTouchListener {
onTouch(View view, MotionEvent event)987         public boolean onTouch(View view, MotionEvent event) {
988             switch (event.getAction()) {
989                 case MotionEvent.ACTION_DOWN:
990                     return true;
991                 case MotionEvent.ACTION_UP:
992                     showOnScreenSettings();
993                     return true;
994             }
995             return false;
996         }
997     }
998 
999     @Override
onStart()1000     public void onStart() {
1001         super.onStart();
1002         if (!mIsImageCaptureIntent) {
1003             mSwitcher.setSwitch(SWITCH_CAMERA);
1004         }
1005     }
1006 
1007     @Override
onStop()1008     public void onStop() {
1009         super.onStop();
1010         if (mMediaProviderClient != null) {
1011             mMediaProviderClient.release();
1012             mMediaProviderClient = null;
1013         }
1014     }
1015 
checkStorage()1016     private void checkStorage() {
1017         if (ImageManager.isMediaScannerScanning(getContentResolver())) {
1018             mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR;
1019         } else {
1020             calculatePicturesRemaining();
1021         }
1022         updateStorageHint(mPicturesRemaining);
1023     }
1024 
1025 
showOnScreenSettings()1026     private void showOnScreenSettings() {
1027         if (mSettings == null) {
1028             mSettings = new OnScreenSettings(
1029                     findViewById(R.id.camera_preview));
1030             CameraSettings helper =
1031                     new CameraSettings(this, mInitialParams);
1032             mSettings.setPreferenceScreen(helper
1033                     .getPreferenceScreen(R.xml.camera_preferences));
1034             mSettings.setOnVisibilityChangedListener(this);
1035 
1036             String sceneMode = mParameters.getSceneMode();
1037             if (sceneMode == null
1038                     || Parameters.SCENE_MODE_AUTO.equals(sceneMode)) {
1039                 // If scene mode is auto, cancel override in settings
1040                 mSettings.overrideSettings(CameraSettings.KEY_FLASH_MODE, null);
1041                 mSettings.overrideSettings(CameraSettings.KEY_FOCUS_MODE, null);
1042                 mSettings.overrideSettings(
1043                         CameraSettings.KEY_WHITE_BALANCE, null);
1044             } else {
1045                 // If scene mode is not auto, override the value in settings
1046                 mSettings.overrideSettings(CameraSettings.KEY_FLASH_MODE,
1047                         mParameters.getFlashMode());
1048                 mSettings.overrideSettings(CameraSettings.KEY_FOCUS_MODE,
1049                         mParameters.getFocusMode());
1050                 mSettings.overrideSettings(CameraSettings.KEY_WHITE_BALANCE,
1051                         mParameters.getWhiteBalance());
1052             }
1053         }
1054 
1055         mSettings.setVisible(true);
1056     }
1057 
onClick(View v)1058     public void onClick(View v) {
1059         switch (v.getId()) {
1060             case R.id.btn_retake:
1061                 hidePostCaptureAlert();
1062                 restartPreview();
1063                 break;
1064             case R.id.review_thumbnail:
1065                 if (isCameraIdle()) {
1066                     viewLastImage();
1067                 }
1068                 break;
1069             case R.id.btn_done:
1070                 doAttach();
1071                 break;
1072             case R.id.btn_cancel:
1073                 doCancel();
1074         }
1075     }
1076 
createCaptureBitmap(byte[] data)1077     private Bitmap createCaptureBitmap(byte[] data) {
1078         // This is really stupid...we just want to read the orientation in
1079         // the jpeg header.
1080         String filepath = ImageManager.getTempJpegPath();
1081         int degree = 0;
1082         if (saveDataToFile(filepath, data)) {
1083             degree = ImageManager.getExifOrientation(filepath);
1084             new File(filepath).delete();
1085         }
1086 
1087         // Limit to 50k pixels so we can return it in the intent.
1088         Bitmap bitmap = Util.makeBitmap(data, 50*1024);
1089         bitmap = Util.rotate(bitmap, degree);
1090         return bitmap;
1091     }
1092 
doAttach()1093     private void doAttach() {
1094         if (mPausing) {
1095             return;
1096         }
1097 
1098         byte[] data = mImageCapture.getLastCaptureData();
1099 
1100         if (mCropValue == null) {
1101             // First handle the no crop case -- just return the value.  If the
1102             // caller specifies a "save uri" then write the data to it's
1103             // stream. Otherwise, pass back a scaled down version of the bitmap
1104             // directly in the extras.
1105             if (mSaveUri != null) {
1106                 OutputStream outputStream = null;
1107                 try {
1108                     outputStream = mContentResolver.openOutputStream(mSaveUri);
1109                     outputStream.write(data);
1110                     outputStream.close();
1111 
1112                     setResult(RESULT_OK);
1113                     finish();
1114                 } catch (IOException ex) {
1115                     // ignore exception
1116                 } finally {
1117                     Util.closeSilently(outputStream);
1118                 }
1119             } else {
1120                 Bitmap bitmap = createCaptureBitmap(data);
1121                 setResult(RESULT_OK,
1122                         new Intent("inline-data").putExtra("data", bitmap));
1123                 finish();
1124             }
1125         } else {
1126             // Save the image to a temp file and invoke the cropper
1127             Uri tempUri = null;
1128             FileOutputStream tempStream = null;
1129             try {
1130                 File path = getFileStreamPath(sTempCropFilename);
1131                 path.delete();
1132                 tempStream = openFileOutput(sTempCropFilename, 0);
1133                 tempStream.write(data);
1134                 tempStream.close();
1135                 tempUri = Uri.fromFile(path);
1136             } catch (FileNotFoundException ex) {
1137                 setResult(Activity.RESULT_CANCELED);
1138                 finish();
1139                 return;
1140             } catch (IOException ex) {
1141                 setResult(Activity.RESULT_CANCELED);
1142                 finish();
1143                 return;
1144             } finally {
1145                 Util.closeSilently(tempStream);
1146             }
1147 
1148             Bundle newExtras = new Bundle();
1149             if (mCropValue.equals("circle")) {
1150                 newExtras.putString("circleCrop", "true");
1151             }
1152             if (mSaveUri != null) {
1153                 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1154             } else {
1155                 newExtras.putBoolean("return-data", true);
1156             }
1157 
1158             Intent cropIntent = new Intent("com.android.camera.action.CROP");
1159 
1160             cropIntent.setData(tempUri);
1161             cropIntent.putExtras(newExtras);
1162 
1163             startActivityForResult(cropIntent, CROP_MSG);
1164         }
1165     }
1166 
doCancel()1167     private void doCancel() {
1168         setResult(RESULT_CANCELED, new Intent());
1169         finish();
1170     }
1171 
onShutterButtonFocus(ShutterButton button, boolean pressed)1172     public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1173         if (mPausing) {
1174             return;
1175         }
1176         switch (button.getId()) {
1177             case R.id.shutter_button:
1178                 doFocus(pressed);
1179                 break;
1180         }
1181     }
1182 
onShutterButtonClick(ShutterButton button)1183     public void onShutterButtonClick(ShutterButton button) {
1184         if (mPausing) {
1185             return;
1186         }
1187         switch (button.getId()) {
1188             case R.id.shutter_button:
1189                 doSnap();
1190                 break;
1191         }
1192     }
1193 
1194     private OnScreenHint mStorageHint;
1195 
updateStorageHint(int remaining)1196     private void updateStorageHint(int remaining) {
1197         String noStorageText = null;
1198 
1199         if (remaining == MenuHelper.NO_STORAGE_ERROR) {
1200             String state = Environment.getExternalStorageState();
1201             if (state == Environment.MEDIA_CHECKING ||
1202                     ImageManager.isMediaScannerScanning(getContentResolver())) {
1203                 noStorageText = getString(R.string.preparing_sd);
1204             } else {
1205                 noStorageText = getString(R.string.no_storage);
1206             }
1207         } else if (remaining < 1) {
1208             noStorageText = getString(R.string.not_enough_space);
1209         }
1210 
1211         if (noStorageText != null) {
1212             if (mStorageHint == null) {
1213                 mStorageHint = OnScreenHint.makeText(this, noStorageText);
1214             } else {
1215                 mStorageHint.setText(noStorageText);
1216             }
1217             mStorageHint.show();
1218         } else if (mStorageHint != null) {
1219             mStorageHint.cancel();
1220             mStorageHint = null;
1221         }
1222     }
1223 
installIntentFilter()1224     private void installIntentFilter() {
1225         // install an intent filter to receive SD card related events.
1226         IntentFilter intentFilter =
1227                 new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1228         intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1229         intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
1230         intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1231         intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1232         intentFilter.addDataScheme("file");
1233         registerReceiver(mReceiver, intentFilter);
1234         mDidRegister = true;
1235     }
1236 
initializeFocusTone()1237     private void initializeFocusTone() {
1238         // Initialize focus tone generator.
1239         try {
1240             mFocusToneGenerator = new ToneGenerator(
1241                     AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1242         } catch (Throwable ex) {
1243             Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1244             mFocusToneGenerator = null;
1245         }
1246     }
1247 
readPreference()1248     private void readPreference() {
1249         mRecordLocation = mPreferences.getBoolean(
1250                 "pref_camera_recordlocation_key", false);
1251         mFocusMode = mPreferences.getString(
1252                 CameraSettings.KEY_FOCUS_MODE,
1253                 getString(R.string.pref_camera_focusmode_default));
1254     }
1255 
1256     @Override
onResume()1257     public void onResume() {
1258         super.onResume();
1259 
1260         mPausing = false;
1261         mJpegPictureCallbackTime = 0;
1262         mZoomValue = 0;
1263         mImageCapture = new ImageCapture();
1264 
1265         // Start the preview if it is not started.
1266         if (!mPreviewing && !mStartPreviewFail) {
1267             try {
1268                 startPreview();
1269             } catch (CameraHardwareException e) {
1270                 showCameraErrorAndFinish();
1271                 return;
1272             }
1273         }
1274 
1275         if (mSurfaceHolder != null) {
1276             // If first time initialization is not finished, put it in the
1277             // message queue.
1278             if (!mFirstTimeInitialized) {
1279                 mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1280             } else {
1281                 initializeSecondTime();
1282             }
1283         }
1284         keepScreenOnAwhile();
1285     }
1286 
dataLocation()1287     private static ImageManager.DataLocation dataLocation() {
1288         return ImageManager.DataLocation.EXTERNAL;
1289     }
1290 
1291     @Override
onPause()1292     protected void onPause() {
1293         mPausing = true;
1294         stopPreview();
1295         // Close the camera now because other activities may need to use it.
1296         closeCamera();
1297         resetScreenOn();
1298 
1299         if (mSettings != null && mSettings.isVisible()) {
1300             mSettings.setVisible(false);
1301         }
1302 
1303         if (mFirstTimeInitialized) {
1304             mOrientationListener.disable();
1305             mGpsIndicator.setMode(GPS_MODE_OFF);
1306             if (!mIsImageCaptureIntent) {
1307                 mThumbController.storeData(
1308                         ImageManager.getLastImageThumbPath());
1309             }
1310             hidePostCaptureAlert();
1311         }
1312 
1313         if (mDidRegister) {
1314             unregisterReceiver(mReceiver);
1315             mDidRegister = false;
1316         }
1317         stopReceivingLocationUpdates();
1318 
1319         if (mFocusToneGenerator != null) {
1320             mFocusToneGenerator.release();
1321             mFocusToneGenerator = null;
1322         }
1323 
1324         if (mStorageHint != null) {
1325             mStorageHint.cancel();
1326             mStorageHint = null;
1327         }
1328 
1329         // If we are in an image capture intent and has taken
1330         // a picture, we just clear it in onPause.
1331         mImageCapture.clearLastData();
1332         mImageCapture = null;
1333 
1334         // This is necessary to make the ZoomButtonsController unregister
1335         // its configuration change receiver.
1336         if (mZoomButtons != null) {
1337             mZoomButtons.setVisible(false);
1338         }
1339 
1340         // Remove the messages in the event queue.
1341         mHandler.removeMessages(RESTART_PREVIEW);
1342         mHandler.removeMessages(FIRST_TIME_INIT);
1343 
1344         super.onPause();
1345     }
1346 
1347     @Override
onActivityResult( int requestCode, int resultCode, Intent data)1348     protected void onActivityResult(
1349             int requestCode, int resultCode, Intent data) {
1350         switch (requestCode) {
1351             case CROP_MSG: {
1352                 Intent intent = new Intent();
1353                 if (data != null) {
1354                     Bundle extras = data.getExtras();
1355                     if (extras != null) {
1356                         intent.putExtras(extras);
1357                     }
1358                 }
1359                 setResult(resultCode, intent);
1360                 finish();
1361 
1362                 File path = getFileStreamPath(sTempCropFilename);
1363                 path.delete();
1364 
1365                 break;
1366             }
1367         }
1368     }
1369 
canTakePicture()1370     private boolean canTakePicture() {
1371         return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1372     }
1373 
autoFocus()1374     private void autoFocus() {
1375         // Initiate autofocus only when preview is started and snapshot is not
1376         // in progress.
1377         if (canTakePicture()) {
1378             Log.v(TAG, "Start autofocus.");
1379             if (mZoomButtons != null) mZoomButtons.setVisible(false);
1380             mFocusStartTime = System.currentTimeMillis();
1381             mFocusState = FOCUSING;
1382             updateFocusIndicator();
1383             mCameraDevice.autoFocus(mAutoFocusCallback);
1384         }
1385     }
1386 
cancelAutoFocus()1387     private void cancelAutoFocus() {
1388         // User releases half-pressed focus key.
1389         if (mFocusState == FOCUSING || mFocusState == FOCUS_SUCCESS
1390                 || mFocusState == FOCUS_FAIL) {
1391             Log.v(TAG, "Cancel autofocus.");
1392             mCameraDevice.cancelAutoFocus();
1393         }
1394         if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1395             clearFocusState();
1396         }
1397     }
1398 
clearFocusState()1399     private void clearFocusState() {
1400         mFocusState = FOCUS_NOT_STARTED;
1401         updateFocusIndicator();
1402     }
1403 
updateFocusIndicator()1404     private void updateFocusIndicator() {
1405         if (mFocusRectangle == null) return;
1406 
1407         if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1408             mFocusRectangle.showStart();
1409         } else if (mFocusState == FOCUS_SUCCESS) {
1410             mFocusRectangle.showSuccess();
1411         } else if (mFocusState == FOCUS_FAIL) {
1412             mFocusRectangle.showFail();
1413         } else {
1414             mFocusRectangle.clear();
1415         }
1416     }
1417 
1418     @Override
onBackPressed()1419     public void onBackPressed() {
1420         if (!isCameraIdle()) {
1421             // ignore backs while we're taking a picture
1422             return;
1423         }
1424         super.onBackPressed();
1425     }
1426 
1427     @Override
onKeyDown(int keyCode, KeyEvent event)1428     public boolean onKeyDown(int keyCode, KeyEvent event) {
1429         switch (keyCode) {
1430             case KeyEvent.KEYCODE_FOCUS:
1431                 if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1432                     doFocus(true);
1433                 }
1434                 return true;
1435             case KeyEvent.KEYCODE_CAMERA:
1436                 if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1437                     doSnap();
1438                 }
1439                 return true;
1440             case KeyEvent.KEYCODE_DPAD_CENTER:
1441                 // If we get a dpad center event without any focused view, move
1442                 // the focus to the shutter button and press it.
1443                 if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1444                     // Start auto-focus immediately to reduce shutter lag. After
1445                     // the shutter button gets the focus, doFocus() will be
1446                     // called again but it is fine.
1447                     doFocus(true);
1448                     if (mShutterButton.isInTouchMode()) {
1449                         mShutterButton.requestFocusFromTouch();
1450                     } else {
1451                         mShutterButton.requestFocus();
1452                     }
1453                     mShutterButton.setPressed(true);
1454                 }
1455                 return true;
1456         }
1457 
1458         return super.onKeyDown(keyCode, event);
1459     }
1460 
1461     @Override
onKeyUp(int keyCode, KeyEvent event)1462     public boolean onKeyUp(int keyCode, KeyEvent event) {
1463         switch (keyCode) {
1464             case KeyEvent.KEYCODE_FOCUS:
1465                 if (mFirstTimeInitialized) {
1466                     doFocus(false);
1467                 }
1468                 return true;
1469             case KeyEvent.KEYCODE_MENU:
1470                 if (mIsImageCaptureIntent) {
1471                     showOnScreenSettings();
1472                     return true;
1473                 }
1474                 break;
1475         }
1476         return super.onKeyUp(keyCode, event);
1477     }
1478 
doSnap()1479     private void doSnap() {
1480         Log.v(TAG, "doSnap: mFocusState=" + mFocusState);
1481         // If the user has half-pressed the shutter and focus is completed, we
1482         // can take the photo right away. If the focus mode is infinity, we can
1483         // also take the photo.
1484         if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1485                 || (mFocusState == FOCUS_SUCCESS
1486                 || mFocusState == FOCUS_FAIL)) {
1487             if (mZoomButtons != null) mZoomButtons.setVisible(false);
1488             mImageCapture.onSnap();
1489         } else if (mFocusState == FOCUSING) {
1490             // Half pressing the shutter (i.e. the focus button event) will
1491             // already have requested AF for us, so just request capture on
1492             // focus here.
1493             mFocusState = FOCUSING_SNAP_ON_FINISH;
1494         } else if (mFocusState == FOCUS_NOT_STARTED) {
1495             // Focus key down event is dropped for some reasons. Just ignore.
1496         }
1497     }
1498 
doFocus(boolean pressed)1499     private void doFocus(boolean pressed) {
1500         // Do the focus if the mode is not infinity.
1501         if (!mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)) {
1502             if (pressed) {  // Focus key down.
1503                 autoFocus();
1504             } else {  // Focus key up.
1505                 cancelAutoFocus();
1506             }
1507         }
1508     }
1509 
surfaceChanged(SurfaceHolder holder, int format, int w, int h)1510     public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1511         // Make sure we have a surface in the holder before proceeding.
1512         if (holder.getSurface() == null) {
1513             Log.d(TAG, "holder.getSurface() == null");
1514             return;
1515         }
1516 
1517         // The mCameraDevice will be null if it fails to connect to the camera
1518         // hardware. In this case we will show a dialog and then finish the
1519         // activity, so it's OK to ignore it.
1520         if (mCameraDevice == null) return;
1521 
1522         mSurfaceHolder = holder;
1523 
1524         // Sometimes surfaceChanged is called after onPause. Ignore it.
1525         if (mPausing || isFinishing()) return;
1526 
1527         // Set preview display if the surface is being created. Preview was
1528         // already started.
1529         if (holder.isCreating()) {
1530             setPreviewDisplay(holder);
1531         }
1532 
1533         // If first time initialization is not finished, send a message to do
1534         // it later. We want to finish surfaceChanged as soon as possible to let
1535         // user see preview first.
1536         if (!mFirstTimeInitialized) {
1537             mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1538         } else {
1539             initializeSecondTime();
1540         }
1541     }
1542 
surfaceCreated(SurfaceHolder holder)1543     public void surfaceCreated(SurfaceHolder holder) {
1544     }
1545 
surfaceDestroyed(SurfaceHolder holder)1546     public void surfaceDestroyed(SurfaceHolder holder) {
1547         stopPreview();
1548         mSurfaceHolder = null;
1549     }
1550 
closeCamera()1551     private void closeCamera() {
1552         if (mCameraDevice != null) {
1553             CameraHolder.instance().release();
1554             if (mZoomButtons != null) mCameraDevice.setZoomCallback(null);
1555             mCameraDevice = null;
1556             mPreviewing = false;
1557         }
1558     }
1559 
ensureCameraDevice()1560     private void ensureCameraDevice() throws CameraHardwareException {
1561         if (mCameraDevice == null) {
1562             mCameraDevice = CameraHolder.instance().open();
1563             mInitialParams = mCameraDevice.getParameters();
1564         }
1565     }
1566 
updateLastImage()1567     private void updateLastImage() {
1568         IImageList list = ImageManager.makeImageList(
1569             mContentResolver,
1570             dataLocation(),
1571             ImageManager.INCLUDE_IMAGES,
1572             ImageManager.SORT_ASCENDING,
1573             ImageManager.CAMERA_IMAGE_BUCKET_ID);
1574         int count = list.getCount();
1575         if (count > 0) {
1576             IImage image = list.getImageAt(count - 1);
1577             Uri uri = image.fullSizeImageUri();
1578             mThumbController.setData(uri, image.miniThumbBitmap());
1579         } else {
1580             mThumbController.setData(null, null);
1581         }
1582         list.close();
1583     }
1584 
showCameraErrorAndFinish()1585     private void showCameraErrorAndFinish() {
1586         Resources ress = getResources();
1587         Util.showFatalErrorAndFinish(Camera.this,
1588                 ress.getString(R.string.camera_error_title),
1589                 ress.getString(R.string.cannot_connect_camera));
1590     }
1591 
restartPreview()1592     private void restartPreview() {
1593         // make sure the surfaceview fills the whole screen when previewing
1594         try {
1595             startPreview();
1596         } catch (CameraHardwareException e) {
1597             showCameraErrorAndFinish();
1598             return;
1599         }
1600     }
1601 
setPreviewDisplay(SurfaceHolder holder)1602     private void setPreviewDisplay(SurfaceHolder holder) {
1603         try {
1604             mCameraDevice.setPreviewDisplay(holder);
1605         } catch (Throwable ex) {
1606             closeCamera();
1607             throw new RuntimeException("setPreviewDisplay failed", ex);
1608         }
1609     }
1610 
startPreview()1611     private void startPreview() throws CameraHardwareException {
1612         if (mPausing || isFinishing()) return;
1613 
1614         ensureCameraDevice();
1615 
1616         // If we're previewing already, stop the preview first (this will blank
1617         // the screen).
1618         if (mPreviewing) stopPreview();
1619 
1620         setPreviewDisplay(mSurfaceHolder);
1621         setCameraParameters();
1622 
1623         final long wallTimeStart = SystemClock.elapsedRealtime();
1624         final long threadTimeStart = Debug.threadCpuTimeNanos();
1625 
1626         // Set one shot preview callback for latency measurement.
1627         mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback);
1628         mCameraDevice.setErrorCallback(mErrorCallback);
1629 
1630         try {
1631             Log.v(TAG, "startPreview");
1632             mCameraDevice.startPreview();
1633         } catch (Throwable ex) {
1634             closeCamera();
1635             throw new RuntimeException("startPreview failed", ex);
1636         }
1637         mPreviewing = true;
1638         mZooming = false;
1639         mStatus = IDLE;
1640 
1641         long threadTimeEnd = Debug.threadCpuTimeNanos();
1642         long wallTimeEnd = SystemClock.elapsedRealtime();
1643         if ((wallTimeEnd - wallTimeStart) > 3000) {
1644             Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart)
1645                     + " ms. Thread time was"
1646                     + (threadTimeEnd - threadTimeStart) / 1000000 + " ms.");
1647         }
1648     }
1649 
stopPreview()1650     private void stopPreview() {
1651         if (mCameraDevice != null && mPreviewing) {
1652             Log.v(TAG, "stopPreview");
1653             mCameraDevice.stopPreview();
1654         }
1655         mPreviewing = false;
1656         // If auto focus was in progress, it would have been canceled.
1657         clearFocusState();
1658     }
1659 
getOptimalPreviewSize(List<Size> sizes, double targetRatio)1660     private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
1661         final double ASPECT_TOLERANCE = 0.05;
1662         if (sizes == null) return null;
1663 
1664         Size optimalSize = null;
1665         double minDiff = Double.MAX_VALUE;
1666 
1667         // Because of bugs of overlay and layout, we sometimes will try to
1668         // layout the viewfinder in the portrait orientation and thus get the
1669         // wrong size of mSurfaceView. When we change the preview size, the
1670         // new overlay will be created before the old one closed, which causes
1671         // an exception. For now, just get the screen size
1672 
1673         Display display = getWindowManager().getDefaultDisplay();
1674         int targetHeight = Math.min(display.getHeight(), display.getWidth());
1675 
1676         if (targetHeight <= 0) {
1677             // We don't know the size of SurefaceView, use screen height
1678             WindowManager windowManager = (WindowManager)
1679                     getSystemService(Context.WINDOW_SERVICE);
1680             targetHeight = windowManager.getDefaultDisplay().getHeight();
1681         }
1682 
1683         // Try to find an size match aspect ratio and size
1684         for (Size size : sizes) {
1685             double ratio = (double) size.width / size.height;
1686             if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
1687             if (Math.abs(size.height - targetHeight) < minDiff) {
1688                 optimalSize = size;
1689                 minDiff = Math.abs(size.height - targetHeight);
1690             }
1691         }
1692 
1693         // Cannot find the one match the aspect ratio, ignore the requirement
1694         if (optimalSize == null) {
1695             Log.v(TAG, "No preview size match the aspect ratio");
1696             minDiff = Double.MAX_VALUE;
1697             for (Size size : sizes) {
1698                 if (Math.abs(size.height - targetHeight) < minDiff) {
1699                     optimalSize = size;
1700                     minDiff = Math.abs(size.height - targetHeight);
1701                 }
1702             }
1703         }
1704         Log.v(TAG, String.format(
1705                 "Optimal preview size is %sx%s",
1706                 optimalSize.width, optimalSize.height));
1707         return optimalSize;
1708     }
1709 
isSupported(String value, List<String> supported)1710     private static boolean isSupported(String value, List<String> supported) {
1711         return supported == null ? false : supported.indexOf(value) >= 0;
1712     }
1713 
setCameraParameters()1714     private void setCameraParameters() {
1715         mParameters = mCameraDevice.getParameters();
1716 
1717         // Since change scene mode may change supported values,
1718         // Set scene mode first,
1719         String sceneMode = mPreferences.getString(
1720                 CameraSettings.KEY_SCENE_MODE,
1721                 getString(R.string.pref_camera_scenemode_default));
1722         if (isSupported(sceneMode, mParameters.getSupportedSceneModes())) {
1723             if (!mParameters.getSceneMode().equals(sceneMode)) {
1724                 mParameters.setSceneMode(sceneMode);
1725                 mCameraDevice.setParameters(mParameters);
1726 
1727                 // Setting scene mode will change the settings of flash mode, white
1728                 // balance, and focus mode. So read back here, so that we know
1729                 // what're the settings
1730                 mParameters = mCameraDevice.getParameters();
1731             }
1732         } else {
1733             sceneMode = mParameters.getSceneMode();
1734             if (sceneMode == null) {
1735                 sceneMode = Parameters.SCENE_MODE_AUTO;
1736             }
1737         }
1738 
1739         // Reset preview frame rate to the maximum because it may be lowered by
1740         // video camera application.
1741         List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1742         if (frameRates != null) {
1743             Integer max = Collections.max(frameRates);
1744             mParameters.setPreviewFrameRate(max);
1745         }
1746 
1747         // Set picture size.
1748         String pictureSize = mPreferences.getString(
1749                 CameraSettings.KEY_PICTURE_SIZE, null);
1750         if (pictureSize == null) {
1751             CameraSettings.initialCameraPictureSize(this, mParameters);
1752         } else {
1753             List<Size> supported = mParameters.getSupportedPictureSizes();
1754             CameraSettings.setCameraPictureSize(
1755                     pictureSize, supported, mParameters);
1756         }
1757 
1758         // Set the preview frame aspect ratio according to the picture size.
1759         Size size = mParameters.getPictureSize();
1760         PreviewFrameLayout frameLayout =
1761                 (PreviewFrameLayout) findViewById(R.id.frame_layout);
1762         frameLayout.setAspectRatio((double) size.width / size.height);
1763 
1764         // Set a preview size that is closest to the viewfinder height and has
1765         // the right aspect ratio.
1766         List<Size> sizes = mParameters.getSupportedPreviewSizes();
1767         Size optimalSize = getOptimalPreviewSize(
1768                 sizes, (double) size.width / size.height);
1769         if (optimalSize != null) {
1770             mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1771         }
1772 
1773         // Set JPEG quality.
1774         String jpegQuality = mPreferences.getString(
1775                 CameraSettings.KEY_JPEG_QUALITY,
1776                 getString(R.string.pref_camera_jpegquality_default));
1777         mParameters.setJpegQuality(getQualityNumber(jpegQuality));
1778 
1779         // Set zoom.
1780         if (mParameters.isZoomSupported()) {
1781             mParameters.setZoom(mZoomValue);
1782         }
1783 
1784         // For the following settings, we need to check if the settings are
1785         // still supported by latest driver, if not, ignore the settings.
1786 
1787         // Set color effect parameter.
1788         String colorEffect = mPreferences.getString(
1789                 CameraSettings.KEY_COLOR_EFFECT,
1790                 getString(R.string.pref_camera_coloreffect_default));
1791         if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1792             mParameters.setColorEffect(colorEffect);
1793         }
1794 
1795         // If scene mode is set, we cannot set flash mode, white balance, and
1796         // focus mode, instead, we read it from driver
1797         String flashMode;
1798         String whiteBalance;
1799         if (!Parameters.SCENE_MODE_AUTO.equals(sceneMode)) {
1800             flashMode = mParameters.getFlashMode();
1801             whiteBalance = mParameters.getWhiteBalance();
1802             mFocusMode = mParameters.getFocusMode();
1803             if (mSettings != null) {
1804                 mSettings.overrideSettings(
1805                         CameraSettings.KEY_FLASH_MODE, flashMode);
1806                 mSettings.overrideSettings(
1807                         CameraSettings.KEY_WHITE_BALANCE, whiteBalance);
1808                 mSettings.overrideSettings(
1809                         CameraSettings.KEY_FOCUS_MODE, mFocusMode);
1810             }
1811         } else {
1812             if (mSettings != null) {
1813                 mSettings.overrideSettings(CameraSettings.KEY_FLASH_MODE, null);
1814                 mSettings.overrideSettings(CameraSettings.KEY_FOCUS_MODE, null);
1815                 mSettings.overrideSettings(
1816                         CameraSettings.KEY_WHITE_BALANCE, null);
1817             }
1818 
1819             // Set flash mode.
1820             flashMode = mPreferences.getString(
1821                     CameraSettings.KEY_FLASH_MODE,
1822                     getString(R.string.pref_camera_flashmode_default));
1823             List<String> supportedFlash = mParameters.getSupportedFlashModes();
1824             if (isSupported(flashMode, supportedFlash)) {
1825                 mParameters.setFlashMode(flashMode);
1826             } else {
1827                 flashMode = mParameters.getFlashMode();
1828                 if (flashMode == null) {
1829                     flashMode = Parameters.FLASH_MODE_OFF;
1830                 }
1831             }
1832 
1833             // Set white balance parameter.
1834             whiteBalance = mPreferences.getString(
1835                     CameraSettings.KEY_WHITE_BALANCE,
1836                     getString(R.string.pref_camera_whitebalance_default));
1837             if (isSupported(whiteBalance,
1838                     mParameters.getSupportedWhiteBalance())) {
1839                 mParameters.setWhiteBalance(whiteBalance);
1840             } else {
1841                 whiteBalance = mParameters.getWhiteBalance();
1842                 if (whiteBalance == null) {
1843                     whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1844                 }
1845             }
1846 
1847             // Set focus mode.
1848             mFocusMode = mPreferences.getString(
1849                     CameraSettings.KEY_FOCUS_MODE,
1850                     getString(R.string.pref_camera_focusmode_default));
1851             if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1852                 mParameters.setFocusMode(mFocusMode);
1853             } else {
1854                 mFocusMode = mParameters.getFocusMode();
1855                 if (mFocusMode == null) {
1856                     mFocusMode = Parameters.FOCUS_MODE_AUTO;
1857                 }
1858             }
1859 
1860             mCameraDevice.setParameters(mParameters);
1861         }
1862 
1863         // We post the runner because this function can be called from
1864         // non-UI thread (i.e., startPreviewThread).
1865         final String finalWhiteBalance = whiteBalance;
1866         final String finalFlashMode = flashMode;
1867         final String finalSceneMode =
1868                 Parameters.SCENE_MODE_AUTO.equals(sceneMode)
1869                 ? SCENE_MODE_OFF
1870                 : SCENE_MODE_ON;
1871 
1872         mHandler.post(new Runnable() {
1873             public void run() {
1874                 mFocusIndicator.setMode(mFocusMode);
1875                 mWhitebalanceIndicator.setMode(finalWhiteBalance);
1876                 mSceneModeIndicator.setMode(finalSceneMode);
1877                 mFlashIndicator.setMode(finalFlashMode);
1878             }
1879         });
1880     }
1881 
gotoGallery()1882     private void gotoGallery() {
1883         MenuHelper.gotoCameraImageGallery(this);
1884     }
1885 
viewLastImage()1886     private void viewLastImage() {
1887         if (mThumbController.isUriValid()) {
1888             Uri targetUri = mThumbController.getUri();
1889             targetUri = targetUri.buildUpon().appendQueryParameter(
1890                     "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
1891             Intent intent = new Intent(this, ReviewImage.class);
1892             intent.setData(targetUri);
1893             intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
1894             intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
1895             intent.putExtra("com.android.camera.ReviewMode", true);
1896             try {
1897                 startActivity(intent);
1898             } catch (ActivityNotFoundException ex) {
1899                 Log.e(TAG, "review image fail", ex);
1900             }
1901         } else {
1902             Log.e(TAG, "Can't view last image.");
1903         }
1904     }
1905 
startReceivingLocationUpdates()1906     private void startReceivingLocationUpdates() {
1907         if (mLocationManager != null) {
1908             try {
1909                 mLocationManager.requestLocationUpdates(
1910                         LocationManager.NETWORK_PROVIDER,
1911                         1000,
1912                         0F,
1913                         mLocationListeners[1]);
1914             } catch (java.lang.SecurityException ex) {
1915                 Log.i(TAG, "fail to request location update, ignore", ex);
1916             } catch (IllegalArgumentException ex) {
1917                 Log.d(TAG, "provider does not exist " + ex.getMessage());
1918             }
1919             try {
1920                 mLocationManager.requestLocationUpdates(
1921                         LocationManager.GPS_PROVIDER,
1922                         1000,
1923                         0F,
1924                         mLocationListeners[0]);
1925             } catch (java.lang.SecurityException ex) {
1926                 Log.i(TAG, "fail to request location update, ignore", ex);
1927             } catch (IllegalArgumentException ex) {
1928                 Log.d(TAG, "provider does not exist " + ex.getMessage());
1929             }
1930         }
1931     }
1932 
stopReceivingLocationUpdates()1933     private void stopReceivingLocationUpdates() {
1934         if (mLocationManager != null) {
1935             for (int i = 0; i < mLocationListeners.length; i++) {
1936                 try {
1937                     mLocationManager.removeUpdates(mLocationListeners[i]);
1938                 } catch (Exception ex) {
1939                     Log.i(TAG, "fail to remove location listners, ignore", ex);
1940                 }
1941             }
1942         }
1943     }
1944 
getCurrentLocation()1945     private Location getCurrentLocation() {
1946         // go in best to worst order
1947         for (int i = 0; i < mLocationListeners.length; i++) {
1948             Location l = mLocationListeners[i].current();
1949             if (l != null) return l;
1950         }
1951         return null;
1952     }
1953 
isCameraIdle()1954     private boolean isCameraIdle() {
1955         return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1956     }
1957 
isImageCaptureIntent()1958     private boolean isImageCaptureIntent() {
1959         String action = getIntent().getAction();
1960         return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1961     }
1962 
setupCaptureParams()1963     private void setupCaptureParams() {
1964         Bundle myExtras = getIntent().getExtras();
1965         if (myExtras != null) {
1966             mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1967             mCropValue = myExtras.getString("crop");
1968         }
1969     }
1970 
showPostCaptureAlert()1971     private void showPostCaptureAlert() {
1972         if (mIsImageCaptureIntent) {
1973             findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
1974             int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1975             for (int id : pickIds) {
1976                 View button = findViewById(id);
1977                 ((View) button.getParent()).setVisibility(View.VISIBLE);
1978             }
1979         }
1980     }
1981 
hidePostCaptureAlert()1982     private void hidePostCaptureAlert() {
1983         if (mIsImageCaptureIntent) {
1984             findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
1985             int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1986             for (int id : pickIds) {
1987                 View button = findViewById(id);
1988                 ((View) button.getParent()).setVisibility(View.GONE);
1989             }
1990         }
1991     }
1992 
calculatePicturesRemaining()1993     private int calculatePicturesRemaining() {
1994         mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
1995         return mPicturesRemaining;
1996     }
1997 
1998     @Override
onPrepareOptionsMenu(Menu menu)1999     public boolean onPrepareOptionsMenu(Menu menu) {
2000         super.onPrepareOptionsMenu(menu);
2001         // Only show the menu when camera is idle.
2002         for (int i = 0; i < menu.size(); i++) {
2003             menu.getItem(i).setVisible(isCameraIdle());
2004         }
2005 
2006         return true;
2007     }
2008 
2009     @Override
onCreateOptionsMenu(Menu menu)2010     public boolean onCreateOptionsMenu(Menu menu) {
2011         super.onCreateOptionsMenu(menu);
2012 
2013         if (mIsImageCaptureIntent) {
2014             // No options menu for attach mode.
2015             return false;
2016         } else {
2017             addBaseMenuItems(menu);
2018         }
2019         return true;
2020     }
2021 
addBaseMenuItems(Menu menu)2022     private void addBaseMenuItems(Menu menu) {
2023         MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2024                 MenuHelper.POSITION_GOTO_GALLERY,
2025                 R.string.camera_gallery_photos_text)
2026                 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2027             public boolean onMenuItemClick(MenuItem item) {
2028                 gotoGallery();
2029                 return true;
2030             }
2031         });
2032         gallery.setIcon(android.R.drawable.ic_menu_gallery);
2033         mGalleryItems.add(gallery);
2034 
2035         MenuItem item = menu.add(Menu.NONE, Menu.NONE,
2036                 MenuHelper.POSITION_CAMERA_SETTING, R.string.settings)
2037                 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2038             public boolean onMenuItemClick(MenuItem item) {
2039                 showOnScreenSettings();
2040                 return true;
2041             }
2042         });
2043         item.setIcon(android.R.drawable.ic_menu_preferences);
2044     }
2045 
onSwitchChanged(Switcher source, boolean onOff)2046     public boolean onSwitchChanged(Switcher source, boolean onOff) {
2047         if (onOff == SWITCH_VIDEO) {
2048             if (!isCameraIdle()) return false;
2049             MenuHelper.gotoVideoMode(this);
2050             finish();
2051         }
2052         return true;
2053     }
2054 
onSharedPreferenceChanged( SharedPreferences preferences, String key)2055     public void onSharedPreferenceChanged(
2056             SharedPreferences preferences, String key) {
2057         // ignore the events after "onPause()"
2058         if (mPausing) return;
2059 
2060         if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) {
2061             mRecordLocation = preferences.getBoolean(key, false);
2062             if (mRecordLocation) {
2063                 startReceivingLocationUpdates();
2064             } else {
2065                 stopReceivingLocationUpdates();
2066             }
2067         } else {
2068             // All preferences except RECORD_LOCATION are camera parameters.
2069             // Call setCameraParameters to take effect now.
2070             setCameraParameters();
2071         }
2072     }
2073 
2074     @Override
onUserInteraction()2075     public void onUserInteraction() {
2076         super.onUserInteraction();
2077         keepScreenOnAwhile();
2078     }
2079 
resetScreenOn()2080     private void resetScreenOn() {
2081         mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2082         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2083     }
2084 
keepScreenOnAwhile()2085     private void keepScreenOnAwhile() {
2086         mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2087         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2088         mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2089     }
2090 
2091     private static String[] mQualityStrings = {"superfine", "fine", "normal"};
2092     private static String[] mQualityNumbers = SystemProperties.get(
2093             "ro.media.enc.jpeg.quality", "85,75,65").split(",");
2094     private static int DEFAULT_QUALITY = 85;
2095 
2096     // Translate from a quality string to a quality number using the system
2097     // properties.
getQualityNumber(String jpegQuality)2098     private static int getQualityNumber(String jpegQuality) {
2099         // Find the index of the input string
2100         int index = Util.indexOf(mQualityStrings, jpegQuality);
2101 
2102         if (index == -1 || index > mQualityNumbers.length - 1) {
2103             return DEFAULT_QUALITY;
2104         }
2105 
2106         try {
2107             return Integer.parseInt(mQualityNumbers[index]);
2108         } catch (NumberFormatException ex) {
2109             return DEFAULT_QUALITY;
2110         }
2111     }
2112 }
2113 
2114 class FocusRectangle extends View {
2115 
2116     @SuppressWarnings("unused")
2117     private static final String TAG = "FocusRectangle";
2118 
FocusRectangle(Context context, AttributeSet attrs)2119     public FocusRectangle(Context context, AttributeSet attrs) {
2120         super(context, attrs);
2121     }
2122 
setDrawable(int resid)2123     private void setDrawable(int resid) {
2124         setBackgroundDrawable(getResources().getDrawable(resid));
2125     }
2126 
showStart()2127     public void showStart() {
2128         setDrawable(R.drawable.focus_focusing);
2129     }
2130 
showSuccess()2131     public void showSuccess() {
2132         setDrawable(R.drawable.focus_focused);
2133     }
2134 
showFail()2135     public void showFail() {
2136         setDrawable(R.drawable.focus_focus_failed);
2137     }
2138 
clear()2139     public void clear() {
2140         setBackgroundDrawable(null);
2141     }
2142 }
2143