Camera.java revision c343fa06491ee5677b735920032d92e055c16366
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
17package com.android.camera;
18
19import com.android.camera.ui.CameraPicker;
20import com.android.camera.ui.FaceView;
21import com.android.camera.ui.IndicatorControlContainer;
22import com.android.camera.ui.RotateImageView;
23import com.android.camera.ui.RotateLayout;
24import com.android.camera.ui.SharePopup;
25import com.android.camera.ui.ZoomControl;
26
27import android.app.Activity;
28import android.content.BroadcastReceiver;
29import android.content.ContentProviderClient;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.SharedPreferences.Editor;
35import android.graphics.Bitmap;
36import android.hardware.Camera.CameraInfo;
37import android.hardware.Camera.Face;
38import android.hardware.Camera.FaceDetectionListener;
39import android.hardware.Camera.Parameters;
40import android.hardware.Camera.PictureCallback;
41import android.hardware.Camera.Size;
42import android.location.Location;
43import android.media.CameraProfile;
44import android.net.Uri;
45import android.os.Bundle;
46import android.os.Handler;
47import android.os.Looper;
48import android.os.Message;
49import android.os.MessageQueue;
50import android.os.SystemClock;
51import android.provider.MediaStore;
52import android.provider.Settings;
53import android.util.Log;
54import android.view.GestureDetector;
55import android.view.Gravity;
56import android.view.KeyEvent;
57import android.view.Menu;
58import android.view.MenuItem;
59import android.view.MenuItem.OnMenuItemClickListener;
60import android.view.MotionEvent;
61import android.view.OrientationEventListener;
62import android.view.SurfaceHolder;
63import android.view.SurfaceView;
64import android.view.View;
65import android.view.Window;
66import android.view.WindowManager;
67import android.view.animation.AnimationUtils;
68import android.widget.TextView;
69import android.widget.Toast;
70
71import java.io.File;
72import java.io.FileNotFoundException;
73import java.io.FileOutputStream;
74import java.io.IOException;
75import java.io.OutputStream;
76import java.util.ArrayList;
77import java.util.Collections;
78import java.util.Formatter;
79import java.util.List;
80
81/** The Camera activity which can preview and take pictures. */
82public class Camera extends ActivityBase implements FocusManager.Listener,
83        View.OnTouchListener, ShutterButton.OnShutterButtonListener,
84        SurfaceHolder.Callback, ModePicker.OnModeChangeListener,
85        FaceDetectionListener, CameraPreference.OnPreferenceChangedListener,
86        LocationManager.Listener {
87
88    private static final String TAG = "camera";
89
90    private static final String LAST_THUMB_FILENAME = "image_last_thumb";
91
92    private static final int CROP_MSG = 1;
93    private static final int FIRST_TIME_INIT = 2;
94    private static final int RESTART_PREVIEW = 3;
95    private static final int CLEAR_SCREEN_DELAY = 4;
96    private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 5;
97    private static final int CHECK_DISPLAY_ROTATION = 6;
98    private static final int SHOW_TAP_TO_FOCUS_TOAST = 7;
99    private static final int DISMISS_TAP_TO_FOCUS_TOAST = 8;
100
101    // The subset of parameters we need to update in setCameraParameters().
102    private static final int UPDATE_PARAM_INITIALIZE = 1;
103    private static final int UPDATE_PARAM_ZOOM = 2;
104    private static final int UPDATE_PARAM_PREFERENCE = 4;
105    private static final int UPDATE_PARAM_ALL = -1;
106
107    // When setCameraParametersWhenIdle() is called, we accumulate the subsets
108    // needed to be updated in mUpdateSet.
109    private int mUpdateSet;
110
111    // The brightness settings used when it is set to automatic in the system.
112    // The reason why it is set to 0.7 is just because 1.0 is too bright.
113    private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f;
114
115    private static final int SCREEN_DELAY = 2 * 60 * 1000;
116
117    private static final int ZOOM_STOPPED = 0;
118    private static final int ZOOM_START = 1;
119    private static final int ZOOM_STOPPING = 2;
120
121    private int mZoomState = ZOOM_STOPPED;
122    private boolean mSmoothZoomSupported = false;
123    private int mZoomValue;  // The current zoom value.
124    private int mZoomMax;
125    private int mTargetZoomValue;
126    private ZoomControl mZoomControl;
127
128    private Parameters mParameters;
129    private Parameters mInitialParams;
130    private boolean mFocusAreaSupported;
131    private boolean mMeteringAreaSupported;
132
133    private MyOrientationEventListener mOrientationListener;
134    // The degrees of the device rotated clockwise from its natural orientation.
135    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
136    // The orientation compensation for icons and thumbnails. Ex: if the value
137    // is 90, the UI components should be rotated 90 degrees counter-clockwise.
138    private int mOrientationCompensation = 0;
139    private ComboPreferences mPreferences;
140
141    private static final String sTempCropFilename = "crop-temp";
142
143    private android.hardware.Camera mCameraDevice;
144    private ContentProviderClient mMediaProviderClient;
145    private SurfaceHolder mSurfaceHolder = null;
146    private ShutterButton mShutterButton;
147    private GestureDetector mPopupGestureDetector;
148    private boolean mOpenCameraFail = false;
149    private boolean mCameraDisabled = false;
150
151    private PreviewFrameLayout mPreviewFrameLayout;
152    private View mPreviewFrame;  // Preview frame area.
153    private View mPreviewBorder;
154
155    // A popup window that contains a bigger thumbnail and a list of apps to share.
156    private SharePopup mSharePopup;
157    // The bitmap of the last captured picture thumbnail and the URI of the
158    // original picture.
159    private Thumbnail mThumbnail;
160    // An imageview showing showing the last captured picture thumbnail.
161    private RotateImageView mThumbnailView;
162    private ModePicker mModePicker;
163    private FaceView mFaceView;
164    private RotateLayout mFocusIndicator;
165
166    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
167    private String mCropValue;
168    private Uri mSaveUri;
169
170    // On-screen indicator
171    private View mGpsNoSignalIndicator;
172    private View mGpsHasSignalIndicator;
173    private TextView mExposureIndicator;
174
175    private final StringBuilder mBuilder = new StringBuilder();
176    private final Formatter mFormatter = new Formatter(mBuilder);
177    private final Object[] mFormatterArgs = new Object[1];
178
179    /**
180     * An unpublished intent flag requesting to return as soon as capturing
181     * is completed.
182     *
183     * TODO: consider publishing by moving into MediaStore.
184     */
185    private final static String EXTRA_QUICK_CAPTURE =
186            "android.intent.extra.quickCapture";
187
188    // The display rotation in degrees. This is only valid when mCameraState is
189    // not PREVIEW_STOPPED.
190    private int mDisplayRotation;
191    // The value for android.hardware.Camera.setDisplayOrientation.
192    private int mDisplayOrientation;
193    private boolean mPausing;
194    private boolean mFirstTimeInitialized;
195    private boolean mIsImageCaptureIntent;
196    private boolean mRecordLocation;
197
198    private static final int PREVIEW_STOPPED = 0;
199    private static final int IDLE = 1;  // preview is active
200    // Focus is in progress. The exact focus state is in Focus.java.
201    private static final int FOCUSING = 2;
202    private static final int SNAPSHOT_IN_PROGRESS = 3;
203    private int mCameraState = PREVIEW_STOPPED;
204
205    private ContentResolver mContentResolver;
206    private boolean mDidRegister = false;
207
208    private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
209
210    private LocationManager mLocationManager = null;
211
212    private final ShutterCallback mShutterCallback = new ShutterCallback();
213    private final PostViewPictureCallback mPostViewPictureCallback =
214            new PostViewPictureCallback();
215    private final RawPictureCallback mRawPictureCallback =
216            new RawPictureCallback();
217    private final AutoFocusCallback mAutoFocusCallback =
218            new AutoFocusCallback();
219    private final ZoomListener mZoomListener = new ZoomListener();
220    private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
221
222    private long mFocusStartTime;
223    private long mCaptureStartTime;
224    private long mShutterCallbackTime;
225    private long mPostViewPictureCallbackTime;
226    private long mRawPictureCallbackTime;
227    private long mJpegPictureCallbackTime;
228    private long mOnResumeTime;
229    private long mPicturesRemaining;
230    private byte[] mJpegImageData;
231
232    // These latency time are for the CameraLatency test.
233    public long mAutoFocusTime;
234    public long mShutterLag;
235    public long mShutterToPictureDisplayedTime;
236    public long mPictureDisplayedToJpegCallbackTime;
237    public long mJpegCallbackFinishTime;
238
239    // This handles everything about focus.
240    private FocusManager mFocusManager;
241    private String mSceneMode;
242    private Toast mNotSelectableToast;
243    private Toast mNoShareToast;
244
245    private final Handler mHandler = new MainHandler();
246    private IndicatorControlContainer mIndicatorControlContainer;
247    private PreferenceGroup mPreferenceGroup;
248
249    // multiple cameras support
250    private int mNumberOfCameras;
251    private int mCameraId;
252    private int mFrontCameraId;
253    private int mBackCameraId;
254
255    private boolean mQuickCapture;
256
257    /**
258     * This Handler is used to post message back onto the main thread of the
259     * application
260     */
261    private class MainHandler extends Handler {
262        @Override
263        public void handleMessage(Message msg) {
264            switch (msg.what) {
265                case RESTART_PREVIEW: {
266                    startPreview();
267                    if (mJpegPictureCallbackTime != 0) {
268                        long now = System.currentTimeMillis();
269                        mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
270                        Log.v(TAG, "mJpegCallbackFinishTime = "
271                                + mJpegCallbackFinishTime + "ms");
272                        mJpegPictureCallbackTime = 0;
273                    }
274                    break;
275                }
276
277                case CLEAR_SCREEN_DELAY: {
278                    getWindow().clearFlags(
279                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
280                    break;
281                }
282
283                case FIRST_TIME_INIT: {
284                    initializeFirstTime();
285                    break;
286                }
287
288                case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
289                    setCameraParametersWhenIdle(0);
290                    break;
291                }
292
293                case CHECK_DISPLAY_ROTATION: {
294                    // Restart the preview if display rotation has changed.
295                    // Sometimes this happens when the device is held upside
296                    // down and camera app is opened. Rotation animation will
297                    // take some time and the rotation value we have got may be
298                    // wrong. Framework does not have a callback for this now.
299                    if (Util.getDisplayRotation(Camera.this) != mDisplayRotation
300                            && isCameraIdle()) {
301                        startPreview();
302                    }
303                    if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
304                        mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
305                    }
306                    break;
307                }
308
309                case SHOW_TAP_TO_FOCUS_TOAST: {
310                    showTapToFocusToast();
311                    break;
312                }
313
314                case DISMISS_TAP_TO_FOCUS_TOAST: {
315                    View v = findViewById(R.id.tap_to_focus_prompt);
316                    v.setVisibility(View.GONE);
317                    v.setAnimation(AnimationUtils.loadAnimation(Camera.this,
318                            R.anim.on_screen_hint_exit));
319                    break;
320                }
321            }
322        }
323    }
324
325    private void resetExposureCompensation() {
326        String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
327                CameraSettings.EXPOSURE_DEFAULT_VALUE);
328        if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
329            Editor editor = mPreferences.edit();
330            editor.putString(CameraSettings.KEY_EXPOSURE, "0");
331            editor.apply();
332            if (mIndicatorControlContainer != null) {
333                mIndicatorControlContainer.reloadPreferences();
334            }
335        }
336    }
337
338    private void keepMediaProviderInstance() {
339        // We want to keep a reference to MediaProvider in camera's lifecycle.
340        // TODO: Utilize mMediaProviderClient instance to replace
341        // ContentResolver calls.
342        if (mMediaProviderClient == null) {
343            mMediaProviderClient = getContentResolver()
344                    .acquireContentProviderClient(MediaStore.AUTHORITY);
345        }
346    }
347
348    // Snapshots can only be taken after this is called. It should be called
349    // once only. We could have done these things in onCreate() but we want to
350    // make preview screen appear as soon as possible.
351    private void initializeFirstTime() {
352        if (mFirstTimeInitialized) return;
353
354        // Create orientation listenter. This should be done first because it
355        // takes some time to get first orientation.
356        mOrientationListener = new MyOrientationEventListener(Camera.this);
357        mOrientationListener.enable();
358
359        // Initialize location sevice.
360        mRecordLocation = RecordLocationPreference.get(
361                mPreferences, getContentResolver());
362        initOnScreenIndicator();
363        if (mRecordLocation) mLocationManager.startReceivingLocationUpdates();
364
365        keepMediaProviderInstance();
366        checkStorage();
367
368        // Initialize last picture button.
369        mContentResolver = getContentResolver();
370        if (!mIsImageCaptureIntent) {  // no thumbnail in image capture intent
371            initThumbnailButton();
372        }
373
374        // Initialize shutter button.
375        mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
376        mShutterButton.setOnShutterButtonListener(this);
377        mShutterButton.setVisibility(View.VISIBLE);
378
379        // Initialize focus UI.
380        mPreviewFrame = findViewById(R.id.camera_preview);
381        mPreviewFrame.setOnTouchListener(this);
382        mPreviewBorder = findViewById(R.id.preview_border);
383        mFocusIndicator = (RotateLayout) findViewById(R.id.focus_indicator_rotate_layout);
384        mFocusManager.initialize(mFocusIndicator, mPreviewFrame, mFaceView, this);
385        mFocusManager.initializeToneGenerator();
386        initializeScreenBrightness();
387        installIntentFilter();
388        initializeZoom();
389        // Show the tap to focus toast if this is the first start.
390        if (mFocusAreaSupported &&
391                mPreferences.getBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, true)) {
392            // Delay the toast for one second to wait for orientation.
393            mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
394        }
395
396        mFirstTimeInitialized = true;
397        addIdleHandler();
398    }
399
400    private void addIdleHandler() {
401        MessageQueue queue = Looper.myQueue();
402        queue.addIdleHandler(new MessageQueue.IdleHandler() {
403            public boolean queueIdle() {
404                Storage.ensureOSXCompatible();
405                return false;
406            }
407        });
408    }
409
410    private void initThumbnailButton() {
411        // Load the thumbnail from the disk.
412        mThumbnail = Thumbnail.loadFrom(new File(getFilesDir(), LAST_THUMB_FILENAME));
413        updateThumbnailButton();
414    }
415
416    private void updateThumbnailButton() {
417        // Update last image if URI is invalid and the storage is ready.
418        if ((mThumbnail == null || !Util.isUriValid(mThumbnail.getUri(), mContentResolver))
419                && mPicturesRemaining >= 0) {
420            mThumbnail = Thumbnail.getLastImageThumbnail(mContentResolver);
421        }
422        if (mThumbnail != null) {
423            mThumbnailView.setBitmap(mThumbnail.getBitmap());
424        } else {
425            mThumbnailView.setBitmap(null);
426        }
427    }
428
429    // If the activity is paused and resumed, this method will be called in
430    // onResume.
431    private void initializeSecondTime() {
432        // Start orientation listener as soon as possible because it takes
433        // some time to get first orientation.
434        mOrientationListener.enable();
435
436        // Start location update if needed.
437        mRecordLocation = RecordLocationPreference.get(
438                mPreferences, getContentResolver());
439        if (mRecordLocation) mLocationManager.startReceivingLocationUpdates();
440
441        installIntentFilter();
442        mFocusManager.initializeToneGenerator();
443        initializeZoom();
444        keepMediaProviderInstance();
445        checkStorage();
446
447        if (!mIsImageCaptureIntent) {
448            updateThumbnailButton();
449            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
450        }
451    }
452
453    private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener {
454        // only for immediate zoom
455        @Override
456        public void onZoomValueChanged(int index) {
457            Camera.this.onZoomValueChanged(index);
458        }
459
460        // only for smooth zoom
461        @Override
462        public void onZoomStateChanged(int state) {
463            if (mPausing) return;
464
465            Log.v(TAG, "zoom picker state=" + state);
466            if (state == ZoomControl.ZOOM_IN) {
467                Camera.this.onZoomValueChanged(mZoomMax);
468            } else if (state == ZoomControl.ZOOM_OUT) {
469                Camera.this.onZoomValueChanged(0);
470            } else {
471                mTargetZoomValue = -1;
472                if (mZoomState == ZOOM_START) {
473                    mZoomState = ZOOM_STOPPING;
474                    mCameraDevice.stopSmoothZoom();
475                }
476            }
477        }
478    }
479
480    private void initializeZoom() {
481        if (!mParameters.isZoomSupported()) return;
482        mZoomMax = mParameters.getMaxZoom();
483        mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
484        mZoomControl.setZoomMax(mZoomMax);
485        mZoomControl.setZoomIndex(mParameters.getZoom());
486        mZoomControl.setSmoothZoomSupported(mSmoothZoomSupported);
487        mZoomControl.setOnZoomChangeListener(new ZoomChangeListener());
488        mCameraDevice.setZoomChangeListener(mZoomListener);
489    }
490
491    private void onZoomValueChanged(int index) {
492        // Not useful to change zoom value when the activity is paused.
493        if (mPausing) return;
494
495        if (mSmoothZoomSupported) {
496            if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
497                mTargetZoomValue = index;
498                if (mZoomState == ZOOM_START) {
499                    mZoomState = ZOOM_STOPPING;
500                    mCameraDevice.stopSmoothZoom();
501                }
502            } else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
503                mTargetZoomValue = index;
504                mCameraDevice.startSmoothZoom(index);
505                mZoomState = ZOOM_START;
506            }
507        } else {
508            mZoomValue = index;
509            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
510        }
511    }
512
513    @Override
514    public void startFaceDetection() {
515        if (mParameters.getMaxNumDetectedFaces() > 0) {
516            mFaceView = (FaceView) findViewById(R.id.face_view);
517            mFaceView.clear();
518            mFaceView.setVisibility(View.VISIBLE);
519            mFaceView.setDisplayOrientation(mDisplayOrientation);
520            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
521            mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
522            mFaceView.resume();
523            mCameraDevice.setFaceDetectionListener(this);
524            mCameraDevice.startFaceDetection();
525        }
526    }
527
528    @Override
529    public void stopFaceDetection() {
530        if (mParameters.getMaxNumDetectedFaces() > 0) {
531            mCameraDevice.setFaceDetectionListener(null);
532            mCameraDevice.stopFaceDetection();
533            if (mFaceView != null) mFaceView.clear();
534        }
535    }
536
537    private class PopupGestureListener
538            extends GestureDetector.SimpleOnGestureListener {
539        @Override
540        public boolean onDown(MotionEvent e) {
541            // Check if the popup window is visible.
542            View popup = mIndicatorControlContainer.getActiveSettingPopup();
543            if (popup == null) return false;
544
545
546            // Let popup window, indicator control or preview frame handle the
547            // event by themselves. Dismiss the popup window if users touch on
548            // other areas.
549            if (!Util.pointInView(e.getX(), e.getY(), popup)
550                    && !Util.pointInView(e.getX(), e.getY(), mIndicatorControlContainer)
551                    && !Util.pointInView(e.getX(), e.getY(), mPreviewFrame)) {
552                mIndicatorControlContainer.dismissSettingPopup();
553                // Let event fall through.
554            }
555            return false;
556        }
557    }
558
559    @Override
560    public boolean dispatchTouchEvent(MotionEvent m) {
561        // Check if the popup window should be dismissed first.
562        if (mPopupGestureDetector != null && mPopupGestureDetector.onTouchEvent(m)) {
563            return true;
564        }
565
566        return super.dispatchTouchEvent(m);
567    }
568
569    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
570        @Override
571        public void onReceive(Context context, Intent intent) {
572            String action = intent.getAction();
573            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
574                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
575                    || action.equals(Intent.ACTION_MEDIA_CHECKING)) {
576                checkStorage();
577            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
578                checkStorage();
579                if (!mIsImageCaptureIntent) {
580                    updateThumbnailButton();
581                }
582            }
583        }
584    };
585
586    private void initOnScreenIndicator() {
587        mGpsNoSignalIndicator = findViewById(R.id.onscreen_gps_indicator_no_signal);
588        mGpsHasSignalIndicator = findViewById(R.id.onscreen_gps_indicator_on);
589        mExposureIndicator = (TextView) findViewById(R.id.onscreen_exposure_indicator);
590    }
591
592    @Override
593    public void showGpsOnScreenIndicator(boolean hasSignal) {
594        if (hasSignal) {
595            if (mGpsNoSignalIndicator != null) {
596                mGpsNoSignalIndicator.setVisibility(View.GONE);
597            }
598            if (mGpsHasSignalIndicator != null) {
599                mGpsHasSignalIndicator.setVisibility(View.VISIBLE);
600            }
601        } else {
602            if (mGpsNoSignalIndicator != null) {
603                mGpsNoSignalIndicator.setVisibility(View.VISIBLE);
604            }
605            if (mGpsHasSignalIndicator != null) {
606                mGpsHasSignalIndicator.setVisibility(View.GONE);
607            }
608        }
609    }
610
611    @Override
612    public void hideGpsOnScreenIndicator() {
613        if (mGpsNoSignalIndicator != null) mGpsNoSignalIndicator.setVisibility(View.GONE);
614        if (mGpsHasSignalIndicator != null) mGpsHasSignalIndicator.setVisibility(View.GONE);
615    }
616
617    private void updateExposureOnScreenIndicator(int value) {
618        if (mExposureIndicator == null) return;
619
620        if (value == 0) {
621            mExposureIndicator.setText("");
622            mExposureIndicator.setVisibility(View.GONE);
623        } else {
624            float step = mParameters.getExposureCompensationStep();
625            mFormatterArgs[0] = value * step;
626            mBuilder.delete(0, mBuilder.length());
627            mFormatter.format("%+1.1f", mFormatterArgs);
628            String exposure = mFormatter.toString();
629            mExposureIndicator.setText(exposure);
630            mExposureIndicator.setVisibility(View.VISIBLE);
631        }
632    }
633
634    private final class ShutterCallback
635            implements android.hardware.Camera.ShutterCallback {
636        public void onShutter() {
637            mShutterCallbackTime = System.currentTimeMillis();
638            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
639            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
640            mFocusManager.onShutter();
641        }
642    }
643
644    private final class PostViewPictureCallback implements PictureCallback {
645        public void onPictureTaken(
646                byte [] data, android.hardware.Camera camera) {
647            mPostViewPictureCallbackTime = System.currentTimeMillis();
648            Log.v(TAG, "mShutterToPostViewCallbackTime = "
649                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
650                    + "ms");
651        }
652    }
653
654    private final class RawPictureCallback implements PictureCallback {
655        public void onPictureTaken(
656                byte [] rawData, android.hardware.Camera camera) {
657            mRawPictureCallbackTime = System.currentTimeMillis();
658            Log.v(TAG, "mShutterToRawCallbackTime = "
659                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
660        }
661    }
662
663    private final class JpegPictureCallback implements PictureCallback {
664        Location mLocation;
665
666        public JpegPictureCallback(Location loc) {
667            mLocation = loc;
668        }
669
670        public void onPictureTaken(
671                final byte [] jpegData, final android.hardware.Camera camera) {
672            if (mPausing) {
673                return;
674            }
675
676            mJpegPictureCallbackTime = System.currentTimeMillis();
677            // If postview callback has arrived, the captured image is displayed
678            // in postview callback. If not, the captured image is displayed in
679            // raw picture callback.
680            if (mPostViewPictureCallbackTime != 0) {
681                mShutterToPictureDisplayedTime =
682                        mPostViewPictureCallbackTime - mShutterCallbackTime;
683                mPictureDisplayedToJpegCallbackTime =
684                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
685            } else {
686                mShutterToPictureDisplayedTime =
687                        mRawPictureCallbackTime - mShutterCallbackTime;
688                mPictureDisplayedToJpegCallbackTime =
689                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
690            }
691            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
692                    + mPictureDisplayedToJpegCallbackTime + "ms");
693
694            if (!mIsImageCaptureIntent) {
695                enableCameraControls(true);
696
697                // We want to show the taken picture for a while, so we wait
698                // for at least 0.5 second before restarting the preview.
699                long delay = 500 - mPictureDisplayedToJpegCallbackTime;
700                if (delay < 0) {
701                    startPreview();
702                } else {
703                    mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
704                }
705            }
706
707            if (!mIsImageCaptureIntent) {
708                storeImage(jpegData, mLocation);
709            } else {
710                mJpegImageData = jpegData;
711                if (!mQuickCapture) {
712                    showPostCaptureAlert();
713                } else {
714                    doAttach();
715                }
716            }
717
718            // Check this in advance of each shot so we don't add to shutter
719            // latency. It's true that someone else could write to the SD card in
720            // the mean time and fill it, but that could have happened between the
721            // shutter press and saving the JPEG too.
722            checkStorage();
723
724            if (!mHandler.hasMessages(RESTART_PREVIEW)) {
725                long now = System.currentTimeMillis();
726                mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
727                Log.v(TAG, "mJpegCallbackFinishTime = "
728                        + mJpegCallbackFinishTime + "ms");
729                mJpegPictureCallbackTime = 0;
730            }
731        }
732    }
733
734    private final class AutoFocusCallback
735            implements android.hardware.Camera.AutoFocusCallback {
736        public void onAutoFocus(
737                boolean focused, android.hardware.Camera camera) {
738            if (mPausing) return;
739
740            mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
741            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
742            mFocusManager.onAutoFocus(focused);
743            // If focus completes and the snapshot is not started, enable the
744            // controls.
745            if (mFocusManager.isFocusCompleted()) {
746                enableCameraControls(true);
747            }
748        }
749    }
750
751    private final class ZoomListener
752            implements android.hardware.Camera.OnZoomChangeListener {
753        @Override
754        public void onZoomChange(
755                int value, boolean stopped, android.hardware.Camera camera) {
756            Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
757            mZoomValue = value;
758
759            // Update the UI when we get zoom value.
760            mZoomControl.setZoomIndex(value);
761
762            // Keep mParameters up to date. We do not getParameter again in
763            // takePicture. If we do not do this, wrong zoom value will be set.
764            mParameters.setZoom(value);
765
766            if (stopped && mZoomState != ZOOM_STOPPED) {
767                if (mTargetZoomValue != -1 && value != mTargetZoomValue) {
768                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
769                    mZoomState = ZOOM_START;
770                } else {
771                    mZoomState = ZOOM_STOPPED;
772                }
773            }
774        }
775    }
776
777    private void storeImage(final byte[] data, Location loc) {
778        long dateTaken = System.currentTimeMillis();
779        String title = Util.createJpegName(dateTaken);
780        int orientation = Exif.getOrientation(data);
781        Uri uri = Storage.addImage(mContentResolver, title, dateTaken,
782                loc, orientation, data);
783        if (uri != null) {
784            // Create a thumbnail whose width is equal or bigger than that of the preview.
785            int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width
786                    / mPreviewFrameLayout.getWidth());
787            int inSampleSize = Integer.highestOneBit(ratio);
788            mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri);
789            if (mThumbnail != null) {
790                mThumbnailView.setBitmap(mThumbnail.getBitmap());
791            }
792            Util.broadcastNewPicture(this, uri);
793        }
794    }
795
796    @Override
797    public boolean capture() {
798        // If we are already in the middle of taking a snapshot then ignore.
799        if (mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) {
800            return false;
801        }
802        mCaptureStartTime = System.currentTimeMillis();
803        mPostViewPictureCallbackTime = 0;
804        enableCameraControls(false);
805        mJpegImageData = null;
806
807        // See android.hardware.Camera.Parameters.setRotation for
808        // documentation.
809        int rotation = 0;
810        if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
811            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
812            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
813                rotation = (info.orientation - mOrientation + 360) % 360;
814            } else {  // back-facing camera
815                rotation = (info.orientation + mOrientation) % 360;
816            }
817        }
818        mParameters.setRotation(rotation);
819
820        // Clear previous GPS location from the parameters.
821        mParameters.removeGpsData();
822
823        // We always encode GpsTimeStamp
824        mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
825
826        // Set GPS location.
827        Location loc = mRecordLocation ? mLocationManager.getCurrentLocation() : null;
828        if (loc != null) {
829            double lat = loc.getLatitude();
830            double lon = loc.getLongitude();
831            boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
832
833            if (hasLatLon) {
834                Log.d(TAG, "Set gps location");
835                mParameters.setGpsLatitude(lat);
836                mParameters.setGpsLongitude(lon);
837                mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
838                if (loc.hasAltitude()) {
839                    mParameters.setGpsAltitude(loc.getAltitude());
840                } else {
841                    // for NETWORK_PROVIDER location provider, we may have
842                    // no altitude information, but the driver needs it, so
843                    // we fake one.
844                    mParameters.setGpsAltitude(0);
845                }
846                if (loc.getTime() != 0) {
847                    // Location.getTime() is UTC in milliseconds.
848                    // gps-timestamp is UTC in seconds.
849                    long utcTimeSeconds = loc.getTime() / 1000;
850                    mParameters.setGpsTimestamp(utcTimeSeconds);
851                }
852            } else {
853                loc = null;
854            }
855        }
856
857        mCameraDevice.setParameters(mParameters);
858
859        mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
860                mPostViewPictureCallback, new JpegPictureCallback(loc));
861        mCameraState = SNAPSHOT_IN_PROGRESS;
862        return true;
863    }
864
865    @Override
866    public void setFocusParameters() {
867        setCameraParameters(UPDATE_PARAM_PREFERENCE);
868    }
869
870    private boolean saveDataToFile(String filePath, byte[] data) {
871        FileOutputStream f = null;
872        try {
873            f = new FileOutputStream(filePath);
874            f.write(data);
875        } catch (IOException e) {
876            return false;
877        } finally {
878            Util.closeSilently(f);
879        }
880        return true;
881    }
882
883    @Override
884    public void onCreate(Bundle icicle) {
885        super.onCreate(icicle);
886
887        mIsImageCaptureIntent = isImageCaptureIntent();
888        setContentView(R.layout.camera);
889        if (mIsImageCaptureIntent) {
890            findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
891        } else {
892            mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
893            mThumbnailView.setVisibility(View.VISIBLE);
894        }
895
896        mPreferences = new ComboPreferences(this);
897        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
898        mFocusManager = new FocusManager(mPreferences,
899                getString(R.string.pref_camera_focusmode_default));
900
901        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
902
903        // Testing purpose. Launch a specific camera through the intent extras.
904        int intentCameraId = Util.getCameraFacingIntentExtras(this);
905        if (intentCameraId != -1) {
906            mCameraId = intentCameraId;
907        }
908
909        mPreferences.setLocalId(this, mCameraId);
910        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
911
912        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
913        mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
914
915        // we need to reset exposure for the preview
916        resetExposureCompensation();
917
918        /*
919         * To reduce startup time, we start the preview in another thread.
920         * We make sure the preview is started at the end of onCreate.
921         */
922        Thread startPreviewThread = new Thread(new Runnable() {
923            public void run() {
924                try {
925                    mCameraDevice = Util.openCamera(Camera.this, mCameraId);
926                    initializeCapabilities();
927                    startPreview();
928                } catch (CameraHardwareException e) {
929                    mOpenCameraFail = true;
930                } catch (CameraDisabledException e) {
931                    mCameraDisabled = true;
932                }
933            }
934        });
935        startPreviewThread.start();
936
937        // don't set mSurfaceHolder here. We have it set ONLY within
938        // surfaceChanged / surfaceDestroyed, other parts of the code
939        // assume that when it is set, the surface is also set.
940        SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
941        SurfaceHolder holder = preview.getHolder();
942        holder.addCallback(this);
943        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
944
945        if (mIsImageCaptureIntent) {
946            setupCaptureParams();
947        } else {
948            mModePicker = (ModePicker) findViewById(R.id.mode_picker);
949            mModePicker.setVisibility(View.VISIBLE);
950            mModePicker.setOnModeChangeListener(this);
951            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
952        }
953
954        mZoomControl = (ZoomControl) findViewById(R.id.zoom_control);
955        mLocationManager = new LocationManager(this, this);
956
957        // Make sure preview is started.
958        try {
959            startPreviewThread.join();
960            if (mOpenCameraFail) {
961                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
962                return;
963            } else if (mCameraDisabled) {
964                Util.showErrorAndFinish(this, R.string.camera_disabled);
965                return;
966            }
967        } catch (InterruptedException ex) {
968            // ignore
969        }
970
971        mBackCameraId = CameraHolder.instance().getBackCameraId();
972        mFrontCameraId = CameraHolder.instance().getFrontCameraId();
973
974        // Do this after starting preview because it depends on camera
975        // parameters.
976        initializeIndicatorControl();
977    }
978
979    private void overrideCameraSettings(final String flashMode,
980            final String whiteBalance, final String focusMode) {
981        if (mIndicatorControlContainer != null) {
982            mIndicatorControlContainer.overrideSettings(
983                    CameraSettings.KEY_FLASH_MODE, flashMode,
984                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
985                    CameraSettings.KEY_FOCUS_MODE, focusMode);
986        }
987    }
988
989    private void updateSceneModeUI() {
990        // If scene mode is set, we cannot set flash mode, white balance, and
991        // focus mode, instead, we read it from driver
992        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
993            overrideCameraSettings(mParameters.getFlashMode(),
994                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
995        } else {
996            overrideCameraSettings(null, null, null);
997        }
998    }
999
1000    private void loadCameraPreferences() {
1001        CameraSettings settings = new CameraSettings(this, mInitialParams,
1002                mCameraId, CameraHolder.instance().getCameraInfo());
1003        mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
1004    }
1005
1006    private void initializeIndicatorControl() {
1007        // setting the indicator buttons.
1008        mIndicatorControlContainer =
1009                (IndicatorControlContainer) findViewById(R.id.indicator_control);
1010        if (mIndicatorControlContainer == null) return;
1011        loadCameraPreferences();
1012        final String[] SETTING_KEYS = {
1013                CameraSettings.KEY_WHITE_BALANCE,
1014                CameraSettings.KEY_SCENE_MODE};
1015        final String[] OTHER_SETTING_KEYS = {
1016                CameraSettings.KEY_RECORD_LOCATION,
1017                CameraSettings.KEY_FOCUS_MODE,
1018                CameraSettings.KEY_EXPOSURE,
1019                CameraSettings.KEY_PICTURE_SIZE};
1020
1021        CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light);
1022        mIndicatorControlContainer.initialize(this, mPreferenceGroup,
1023                CameraSettings.KEY_FLASH_MODE, mParameters.isZoomSupported(),
1024                SETTING_KEYS, OTHER_SETTING_KEYS);
1025        mIndicatorControlContainer.setListener(this);
1026    }
1027
1028    private boolean collapseCameraControls() {
1029        if ((mIndicatorControlContainer != null)
1030                && mIndicatorControlContainer.dismissSettingPopup()) {
1031            return true;
1032        }
1033        return false;
1034    }
1035
1036    private void enableCameraControls(boolean enable) {
1037        if (mIndicatorControlContainer != null) {
1038            mIndicatorControlContainer.setEnabled(enable);
1039        }
1040        if (mModePicker != null) mModePicker.setEnabled(enable);
1041        if (mZoomControl != null) mZoomControl.setEnabled(enable);
1042    }
1043
1044    public static int roundOrientation(int orientation) {
1045        return ((orientation + 45) / 90 * 90) % 360;
1046    }
1047
1048    private class MyOrientationEventListener
1049            extends OrientationEventListener {
1050        public MyOrientationEventListener(Context context) {
1051            super(context);
1052        }
1053
1054        @Override
1055        public void onOrientationChanged(int orientation) {
1056            // We keep the last known orientation. So if the user first orient
1057            // the camera then point the camera to floor or sky, we still have
1058            // the correct orientation.
1059            if (orientation == ORIENTATION_UNKNOWN) return;
1060            mOrientation = roundOrientation(orientation);
1061            // When the screen is unlocked, display rotation may change. Always
1062            // calculate the up-to-date orientationCompensation.
1063            int orientationCompensation = mOrientation
1064                    + Util.getDisplayRotation(Camera.this);
1065            if (mOrientationCompensation != orientationCompensation) {
1066                mOrientationCompensation = orientationCompensation;
1067                setOrientationIndicator(mOrientationCompensation);
1068            }
1069
1070            // Show the toast after getting the first orientation changed.
1071            if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
1072                mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
1073                showTapToFocusToast();
1074            }
1075        }
1076    }
1077
1078    private void setOrientationIndicator(int degree) {
1079        if (mThumbnailView != null) mThumbnailView.setDegree(degree);
1080        if (mModePicker != null) mModePicker.setDegree(degree);
1081        if (mSharePopup != null) mSharePopup.setOrientation(degree);
1082        if (mIndicatorControlContainer != null) mIndicatorControlContainer.setDegree(degree);
1083        if (mZoomControl != null) mZoomControl.setDegree(degree);
1084        if (mFocusIndicator != null) mFocusIndicator.setOrientation(degree);
1085        if (mFaceView != null) mFaceView.setOrientation(degree);
1086    }
1087
1088    @Override
1089    public void onStop() {
1090        super.onStop();
1091        if (mMediaProviderClient != null) {
1092            mMediaProviderClient.release();
1093            mMediaProviderClient = null;
1094        }
1095    }
1096
1097    private void checkStorage() {
1098        mPicturesRemaining = Storage.getAvailableSpace();
1099        if (mPicturesRemaining > 0) {
1100            mPicturesRemaining /= 1500000;
1101        }
1102        updateStorageHint();
1103    }
1104
1105    @OnClickAttr
1106    public void onThumbnailClicked(View v) {
1107        if (isCameraIdle() && mThumbnail != null) {
1108            showSharePopup();
1109        }
1110    }
1111
1112    @OnClickAttr
1113    public void onRetakeButtonClicked(View v) {
1114        hidePostCaptureAlert();
1115        startPreview();
1116    }
1117
1118    @OnClickAttr
1119    public void onDoneButtonClicked(View v) {
1120        doAttach();
1121    }
1122
1123    @OnClickAttr
1124    public void onCancelButtonClicked(View v) {
1125        doCancel();
1126    }
1127
1128    private void doAttach() {
1129        if (mPausing) {
1130            return;
1131        }
1132
1133        byte[] data = mJpegImageData;
1134
1135        if (mCropValue == null) {
1136            // First handle the no crop case -- just return the value.  If the
1137            // caller specifies a "save uri" then write the data to it's
1138            // stream. Otherwise, pass back a scaled down version of the bitmap
1139            // directly in the extras.
1140            if (mSaveUri != null) {
1141                OutputStream outputStream = null;
1142                try {
1143                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1144                    outputStream.write(data);
1145                    outputStream.close();
1146
1147                    setResultEx(RESULT_OK);
1148                    finish();
1149                } catch (IOException ex) {
1150                    // ignore exception
1151                } finally {
1152                    Util.closeSilently(outputStream);
1153                }
1154            } else {
1155                int orientation = Exif.getOrientation(data);
1156                Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1157                bitmap = Util.rotate(bitmap, orientation);
1158                setResultEx(RESULT_OK,
1159                        new Intent("inline-data").putExtra("data", bitmap));
1160                finish();
1161            }
1162        } else {
1163            // Save the image to a temp file and invoke the cropper
1164            Uri tempUri = null;
1165            FileOutputStream tempStream = null;
1166            try {
1167                File path = getFileStreamPath(sTempCropFilename);
1168                path.delete();
1169                tempStream = openFileOutput(sTempCropFilename, 0);
1170                tempStream.write(data);
1171                tempStream.close();
1172                tempUri = Uri.fromFile(path);
1173            } catch (FileNotFoundException ex) {
1174                setResultEx(Activity.RESULT_CANCELED);
1175                finish();
1176                return;
1177            } catch (IOException ex) {
1178                setResultEx(Activity.RESULT_CANCELED);
1179                finish();
1180                return;
1181            } finally {
1182                Util.closeSilently(tempStream);
1183            }
1184
1185            Bundle newExtras = new Bundle();
1186            if (mCropValue.equals("circle")) {
1187                newExtras.putString("circleCrop", "true");
1188            }
1189            if (mSaveUri != null) {
1190                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1191            } else {
1192                newExtras.putBoolean("return-data", true);
1193            }
1194
1195            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1196
1197            cropIntent.setData(tempUri);
1198            cropIntent.putExtras(newExtras);
1199
1200            startActivityForResult(cropIntent, CROP_MSG);
1201        }
1202    }
1203
1204    private void doCancel() {
1205        setResultEx(RESULT_CANCELED, new Intent());
1206        finish();
1207    }
1208
1209    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1210        switch (button.getId()) {
1211            case R.id.shutter_button:
1212                doFocus(pressed);
1213                break;
1214        }
1215    }
1216
1217    public void onShutterButtonClick(ShutterButton button) {
1218        switch (button.getId()) {
1219            case R.id.shutter_button:
1220                doSnap();
1221                break;
1222        }
1223    }
1224
1225    private OnScreenHint mStorageHint;
1226
1227    private void updateStorageHint() {
1228        String noStorageText = null;
1229
1230        if (mPicturesRemaining == Storage.UNAVAILABLE) {
1231            noStorageText = getString(R.string.no_storage);
1232        } else if (mPicturesRemaining == Storage.PREPARING) {
1233            noStorageText = getString(R.string.preparing_sd);
1234        } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) {
1235            noStorageText = getString(R.string.access_sd_fail);
1236        } else if (mPicturesRemaining < 1L) {
1237            noStorageText = getString(R.string.not_enough_space);
1238        }
1239
1240        if (noStorageText != null) {
1241            if (mStorageHint == null) {
1242                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1243            } else {
1244                mStorageHint.setText(noStorageText);
1245            }
1246            mStorageHint.show();
1247        } else if (mStorageHint != null) {
1248            mStorageHint.cancel();
1249            mStorageHint = null;
1250        }
1251    }
1252
1253    private void installIntentFilter() {
1254        // install an intent filter to receive SD card related events.
1255        IntentFilter intentFilter =
1256                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1257        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1258        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1259        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1260        intentFilter.addDataScheme("file");
1261        registerReceiver(mReceiver, intentFilter);
1262        mDidRegister = true;
1263    }
1264
1265    private void initializeScreenBrightness() {
1266        Window win = getWindow();
1267        // Overright the brightness settings if it is automatic
1268        int mode = Settings.System.getInt(
1269                getContentResolver(),
1270                Settings.System.SCREEN_BRIGHTNESS_MODE,
1271                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1272        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1273            WindowManager.LayoutParams winParams = win.getAttributes();
1274            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1275            win.setAttributes(winParams);
1276        }
1277    }
1278
1279    @Override
1280    protected void onResume() {
1281        super.onResume();
1282        mPausing = false;
1283        if (mOpenCameraFail || mCameraDisabled) return;
1284
1285        mJpegPictureCallbackTime = 0;
1286        mZoomValue = 0;
1287
1288        // Start the preview if it is not started.
1289        if (mCameraState == PREVIEW_STOPPED) {
1290            try {
1291                mCameraDevice = Util.openCamera(this, mCameraId);
1292                initializeCapabilities();
1293                resetExposureCompensation();
1294                startPreview();
1295            } catch(CameraHardwareException e) {
1296                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
1297                return;
1298            } catch(CameraDisabledException e) {
1299                Util.showErrorAndFinish(this, R.string.camera_disabled);
1300                return;
1301            }
1302        }
1303
1304        if (mSurfaceHolder != null) {
1305            // If first time initialization is not finished, put it in the
1306            // message queue.
1307            if (!mFirstTimeInitialized) {
1308                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1309            } else {
1310                initializeSecondTime();
1311            }
1312        }
1313        keepScreenOnAwhile();
1314
1315        if (mCameraState == IDLE) {
1316            mOnResumeTime = SystemClock.uptimeMillis();
1317            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
1318        }
1319    }
1320
1321    @Override
1322    protected void onPause() {
1323        mPausing = true;
1324        stopPreview();
1325        // Close the camera now because other activities may need to use it.
1326        closeCamera();
1327        resetScreenOn();
1328
1329        // Clear UI.
1330        collapseCameraControls();
1331        if (mSharePopup != null) mSharePopup.dismiss();
1332        if (mFaceView != null) mFaceView.clear();
1333
1334        if (mFirstTimeInitialized) {
1335            mOrientationListener.disable();
1336            if (!mIsImageCaptureIntent) {
1337                if (mThumbnail != null) {
1338                    mThumbnail.saveTo(new File(getFilesDir(), LAST_THUMB_FILENAME));
1339                }
1340            }
1341            hidePostCaptureAlert();
1342        }
1343
1344        if (mDidRegister) {
1345            unregisterReceiver(mReceiver);
1346            mDidRegister = false;
1347        }
1348        mLocationManager.stopReceivingLocationUpdates();
1349        updateExposureOnScreenIndicator(0);
1350
1351        mFocusManager.releaseToneGenerator();
1352
1353        if (mStorageHint != null) {
1354            mStorageHint.cancel();
1355            mStorageHint = null;
1356        }
1357
1358        // If we are in an image capture intent and has taken
1359        // a picture, we just clear it in onPause.
1360        mJpegImageData = null;
1361
1362        // Remove the messages in the event queue.
1363        mHandler.removeMessages(RESTART_PREVIEW);
1364        mHandler.removeMessages(FIRST_TIME_INIT);
1365        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1366        mFocusManager.removeMessages();
1367
1368        super.onPause();
1369    }
1370
1371    @Override
1372    protected void onActivityResult(
1373            int requestCode, int resultCode, Intent data) {
1374        switch (requestCode) {
1375            case CROP_MSG: {
1376                Intent intent = new Intent();
1377                if (data != null) {
1378                    Bundle extras = data.getExtras();
1379                    if (extras != null) {
1380                        intent.putExtras(extras);
1381                    }
1382                }
1383                setResultEx(resultCode, intent);
1384                finish();
1385
1386                File path = getFileStreamPath(sTempCropFilename);
1387                path.delete();
1388
1389                break;
1390            }
1391        }
1392    }
1393
1394    private boolean canTakePicture() {
1395        return isCameraIdle() && (mPicturesRemaining > 0);
1396    }
1397
1398    @Override
1399    public void autoFocus() {
1400        mFocusStartTime = System.currentTimeMillis();
1401        mCameraDevice.autoFocus(mAutoFocusCallback);
1402        mCameraState = FOCUSING;
1403        enableCameraControls(false);
1404    }
1405
1406    @Override
1407    public void cancelAutoFocus() {
1408        mCameraDevice.cancelAutoFocus();
1409        mCameraState = IDLE;
1410        enableCameraControls(true);
1411        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1412    }
1413
1414    // Preview area is touched. Handle touch focus.
1415    @Override
1416    public boolean onTouch(View v, MotionEvent e) {
1417        if (mPausing || !mFirstTimeInitialized || mCameraState == SNAPSHOT_IN_PROGRESS) {
1418            return false;
1419        }
1420
1421        // Do not trigger touch focus if popup window is opened.
1422        if (collapseCameraControls()) return false;
1423
1424        // Check if metering area or focus area is supported.
1425        if (!mFocusAreaSupported && !mMeteringAreaSupported) return false;
1426
1427        return mFocusManager.onTouch(e);
1428    }
1429
1430    @Override
1431    public void onBackPressed() {
1432        if (!isCameraIdle()) {
1433            // ignore backs while we're taking a picture
1434            return;
1435        } else if (!collapseCameraControls()) {
1436            super.onBackPressed();
1437        }
1438    }
1439
1440    @Override
1441    public boolean onKeyDown(int keyCode, KeyEvent event) {
1442        switch (keyCode) {
1443            case KeyEvent.KEYCODE_FOCUS:
1444                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1445                    doFocus(true);
1446                }
1447                return true;
1448            case KeyEvent.KEYCODE_CAMERA:
1449                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1450                    doSnap();
1451                }
1452                return true;
1453            case KeyEvent.KEYCODE_DPAD_CENTER:
1454                // If we get a dpad center event without any focused view, move
1455                // the focus to the shutter button and press it.
1456                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1457                    // Start auto-focus immediately to reduce shutter lag. After
1458                    // the shutter button gets the focus, doFocus() will be
1459                    // called again but it is fine.
1460                    if (collapseCameraControls()) return true;
1461                    doFocus(true);
1462                    if (mShutterButton.isInTouchMode()) {
1463                        mShutterButton.requestFocusFromTouch();
1464                    } else {
1465                        mShutterButton.requestFocus();
1466                    }
1467                    mShutterButton.setPressed(true);
1468                }
1469                return true;
1470        }
1471
1472        return super.onKeyDown(keyCode, event);
1473    }
1474
1475    @Override
1476    public boolean onKeyUp(int keyCode, KeyEvent event) {
1477        switch (keyCode) {
1478            case KeyEvent.KEYCODE_FOCUS:
1479                if (mFirstTimeInitialized) {
1480                    doFocus(false);
1481                }
1482                return true;
1483        }
1484        return super.onKeyUp(keyCode, event);
1485    }
1486
1487    private void doSnap() {
1488        if (mPausing || collapseCameraControls()) return;
1489
1490        Log.v(TAG, "doSnap: mCameraState=" + mCameraState);
1491        mFocusManager.doSnap();
1492    }
1493
1494    private void doFocus(boolean pressed) {
1495        if (mPausing || collapseCameraControls()) return;
1496
1497        // Do not do focus if there is not enough storage.
1498        if (pressed && !canTakePicture()) return;
1499
1500        mFocusManager.doFocus(pressed);
1501    }
1502
1503    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1504        // Make sure we have a surface in the holder before proceeding.
1505        if (holder.getSurface() == null) {
1506            Log.d(TAG, "holder.getSurface() == null");
1507            return;
1508        }
1509
1510        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1511
1512        // We need to save the holder for later use, even when the mCameraDevice
1513        // is null. This could happen if onResume() is invoked after this
1514        // function.
1515        mSurfaceHolder = holder;
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        // Sometimes surfaceChanged is called after onPause or before onResume.
1523        // Ignore it.
1524        if (mPausing || isFinishing()) return;
1525
1526        // Set preview display if the surface is being created. Preview was
1527        // already started. Also restart the preview if display rotation has
1528        // changed. Sometimes this happens when the device is held in portrait
1529        // and camera app is opened. Rotation animation takes some time and
1530        // display rotation in onCreate may not be what we want.
1531        if (mCameraState != PREVIEW_STOPPED
1532                && (Util.getDisplayRotation(this) == mDisplayRotation)
1533                && holder.isCreating()) {
1534            // Set preview display if the surface is being created and preview
1535            // was already started. That means preview display was set to null
1536            // and we need to set it now.
1537            setPreviewDisplay(holder);
1538        } else {
1539            // 1. Restart the preview if the size of surface was changed. The
1540            // framework may not support changing preview display on the fly.
1541            // 2. Start the preview now if surface was destroyed and preview
1542            // stopped.
1543            startPreview();
1544        }
1545
1546        // If first time initialization is not finished, send a message to do
1547        // it later. We want to finish surfaceChanged as soon as possible to let
1548        // user see preview first.
1549        if (!mFirstTimeInitialized) {
1550            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1551        } else {
1552            initializeSecondTime();
1553        }
1554    }
1555
1556    public void surfaceCreated(SurfaceHolder holder) {
1557    }
1558
1559    public void surfaceDestroyed(SurfaceHolder holder) {
1560        stopPreview();
1561        mSurfaceHolder = null;
1562    }
1563
1564    private void closeCamera() {
1565        if (mCameraDevice != null) {
1566            CameraHolder.instance().release();
1567            mCameraDevice.setZoomChangeListener(null);
1568            mCameraDevice.setFaceDetectionListener(null);
1569            mCameraDevice = null;
1570            mCameraState = PREVIEW_STOPPED;
1571            mFocusManager.onCameraReleased();
1572        }
1573    }
1574
1575    private void setPreviewDisplay(SurfaceHolder holder) {
1576        try {
1577            mCameraDevice.setPreviewDisplay(holder);
1578        } catch (Throwable ex) {
1579            closeCamera();
1580            throw new RuntimeException("setPreviewDisplay failed", ex);
1581        }
1582    }
1583
1584    private void startPreview() {
1585        if (mPausing || isFinishing()) return;
1586
1587        mFocusManager.resetTouchFocus();
1588
1589        mCameraDevice.setErrorCallback(mErrorCallback);
1590
1591        // If we're previewing already, stop the preview first (this will blank
1592        // the screen).
1593        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1594
1595        setPreviewDisplay(mSurfaceHolder);
1596        mDisplayRotation = Util.getDisplayRotation(this);
1597        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
1598        mCameraDevice.setDisplayOrientation(mDisplayOrientation);
1599        if (mFaceView != null) {
1600            mFaceView.setDisplayOrientation(mDisplayOrientation);
1601        }
1602        setCameraParameters(UPDATE_PARAM_ALL);
1603
1604        try {
1605            Log.v(TAG, "startPreview");
1606            mCameraDevice.startPreview();
1607        } catch (Throwable ex) {
1608            closeCamera();
1609            throw new RuntimeException("startPreview failed", ex);
1610        }
1611
1612        startFaceDetection();
1613        mZoomState = ZOOM_STOPPED;
1614        mCameraState = IDLE;
1615        mFocusManager.onPreviewStarted();
1616    }
1617
1618    private void stopPreview() {
1619        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1620            Log.v(TAG, "stopPreview");
1621            mCameraDevice.stopPreview();
1622        }
1623        mCameraState = PREVIEW_STOPPED;
1624        mFocusManager.onPreviewStopped();
1625    }
1626
1627    private static boolean isSupported(String value, List<String> supported) {
1628        return supported == null ? false : supported.indexOf(value) >= 0;
1629    }
1630
1631    private void updateCameraParametersInitialize() {
1632        // Reset preview frame rate to the maximum because it may be lowered by
1633        // video camera application.
1634        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1635        if (frameRates != null) {
1636            Integer max = Collections.max(frameRates);
1637            mParameters.setPreviewFrameRate(max);
1638        }
1639
1640        mParameters.setRecordingHint(false);
1641    }
1642
1643    private void updateCameraParametersZoom() {
1644        // Set zoom.
1645        if (mParameters.isZoomSupported()) {
1646            mParameters.setZoom(mZoomValue);
1647        }
1648    }
1649
1650    private void updateCameraParametersPreference() {
1651        if (mFocusAreaSupported) {
1652            mParameters.setFocusAreas(mFocusManager.getTapArea());
1653        }
1654
1655        if (mMeteringAreaSupported) {
1656            // Use the same area for focus and metering.
1657            mParameters.setMeteringAreas(mFocusManager.getTapArea());
1658        }
1659
1660        // Set picture size.
1661        String pictureSize = mPreferences.getString(
1662                CameraSettings.KEY_PICTURE_SIZE, null);
1663        if (pictureSize == null) {
1664            CameraSettings.initialCameraPictureSize(this, mParameters);
1665        } else {
1666            List<Size> supported = mParameters.getSupportedPictureSizes();
1667            CameraSettings.setCameraPictureSize(
1668                    pictureSize, supported, mParameters);
1669        }
1670
1671        // Set the preview frame aspect ratio according to the picture size.
1672        Size size = mParameters.getPictureSize();
1673
1674        mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame_layout);
1675        mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
1676
1677        // Set a preview size that is closest to the viewfinder height and has
1678        // the right aspect ratio.
1679        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1680        Size optimalSize = Util.getOptimalPreviewSize(this,
1681                sizes, (double) size.width / size.height);
1682        Size original = mParameters.getPreviewSize();
1683        if (!original.equals(optimalSize)) {
1684            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1685
1686            // Zoom related settings will be changed for different preview
1687            // sizes, so set and read the parameters to get lastest values
1688            mCameraDevice.setParameters(mParameters);
1689            mParameters = mCameraDevice.getParameters();
1690        }
1691        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
1692
1693        // Since change scene mode may change supported values,
1694        // Set scene mode first,
1695        mSceneMode = mPreferences.getString(
1696                CameraSettings.KEY_SCENE_MODE,
1697                getString(R.string.pref_camera_scenemode_default));
1698        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1699            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1700                mParameters.setSceneMode(mSceneMode);
1701                mCameraDevice.setParameters(mParameters);
1702
1703                // Setting scene mode will change the settings of flash mode,
1704                // white balance, and focus mode. Here we read back the
1705                // parameters, so we can know those settings.
1706                mParameters = mCameraDevice.getParameters();
1707            }
1708        } else {
1709            mSceneMode = mParameters.getSceneMode();
1710            if (mSceneMode == null) {
1711                mSceneMode = Parameters.SCENE_MODE_AUTO;
1712            }
1713        }
1714
1715        // Set JPEG quality.
1716        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1717                CameraProfile.QUALITY_HIGH);
1718        mParameters.setJpegQuality(jpegQuality);
1719
1720        // For the following settings, we need to check if the settings are
1721        // still supported by latest driver, if not, ignore the settings.
1722
1723        // Set exposure compensation
1724        int value = CameraSettings.readExposure(mPreferences);
1725        int max = mParameters.getMaxExposureCompensation();
1726        int min = mParameters.getMinExposureCompensation();
1727        if (value >= min && value <= max) {
1728            mParameters.setExposureCompensation(value);
1729        } else {
1730            Log.w(TAG, "invalid exposure range: " + value);
1731        }
1732
1733        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1734            // Set flash mode.
1735            String flashMode = mPreferences.getString(
1736                    CameraSettings.KEY_FLASH_MODE,
1737                    getString(R.string.pref_camera_flashmode_default));
1738            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1739            if (isSupported(flashMode, supportedFlash)) {
1740                mParameters.setFlashMode(flashMode);
1741            } else {
1742                flashMode = mParameters.getFlashMode();
1743                if (flashMode == null) {
1744                    flashMode = getString(
1745                            R.string.pref_camera_flashmode_no_flash);
1746                }
1747            }
1748
1749            // Set white balance parameter.
1750            String whiteBalance = mPreferences.getString(
1751                    CameraSettings.KEY_WHITE_BALANCE,
1752                    getString(R.string.pref_camera_whitebalance_default));
1753            if (isSupported(whiteBalance,
1754                    mParameters.getSupportedWhiteBalance())) {
1755                mParameters.setWhiteBalance(whiteBalance);
1756            } else {
1757                whiteBalance = mParameters.getWhiteBalance();
1758                if (whiteBalance == null) {
1759                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1760                }
1761            }
1762
1763            // Set focus mode.
1764            mFocusManager.overrideFocusMode(null);
1765            mParameters.setFocusMode(mFocusManager.getFocusMode());
1766        } else {
1767            mFocusManager.overrideFocusMode(mParameters.getFocusMode());
1768        }
1769    }
1770
1771    // We separate the parameters into several subsets, so we can update only
1772    // the subsets actually need updating. The PREFERENCE set needs extra
1773    // locking because the preference can be changed from GLThread as well.
1774    private void setCameraParameters(int updateSet) {
1775        mParameters = mCameraDevice.getParameters();
1776
1777        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1778            updateCameraParametersInitialize();
1779        }
1780
1781        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1782            updateCameraParametersZoom();
1783        }
1784
1785        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1786            updateCameraParametersPreference();
1787        }
1788
1789        mCameraDevice.setParameters(mParameters);
1790    }
1791
1792    // If the Camera is idle, update the parameters immediately, otherwise
1793    // accumulate them in mUpdateSet and update later.
1794    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1795        mUpdateSet |= additionalUpdateSet;
1796        if (mCameraDevice == null) {
1797            // We will update all the parameters when we open the device, so
1798            // we don't need to do anything now.
1799            mUpdateSet = 0;
1800            return;
1801        } else if (isCameraIdle()) {
1802            setCameraParameters(mUpdateSet);
1803            updateSceneModeUI();
1804            mUpdateSet = 0;
1805        } else {
1806            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1807                mHandler.sendEmptyMessageDelayed(
1808                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1809            }
1810        }
1811    }
1812
1813    private void gotoGallery() {
1814        MenuHelper.gotoCameraImageGallery(this);
1815    }
1816
1817    private boolean isCameraIdle() {
1818        return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted());
1819    }
1820
1821    private boolean isImageCaptureIntent() {
1822        String action = getIntent().getAction();
1823        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1824    }
1825
1826    private void setupCaptureParams() {
1827        Bundle myExtras = getIntent().getExtras();
1828        if (myExtras != null) {
1829            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1830            mCropValue = myExtras.getString("crop");
1831        }
1832    }
1833
1834    private void showPostCaptureAlert() {
1835        if (mIsImageCaptureIntent) {
1836            mShutterButton.setVisibility(View.GONE);
1837            mIndicatorControlContainer.setVisibility(View.GONE);
1838
1839            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1840            for (int id : pickIds) {
1841                Util.fadeIn(findViewById(id));
1842            }
1843        }
1844    }
1845
1846    private void hidePostCaptureAlert() {
1847        if (mIsImageCaptureIntent) {
1848            enableCameraControls(true);
1849
1850            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1851            for (int id : pickIds) {
1852                (findViewById(id)).setVisibility(View.GONE);
1853            }
1854
1855            Util.fadeIn(mShutterButton);
1856            Util.fadeIn(mIndicatorControlContainer);
1857        }
1858    }
1859
1860    @Override
1861    public boolean onPrepareOptionsMenu(Menu menu) {
1862        super.onPrepareOptionsMenu(menu);
1863        // Only show the menu when camera is idle.
1864        for (int i = 0; i < menu.size(); i++) {
1865            menu.getItem(i).setVisible(isCameraIdle());
1866        }
1867
1868        return true;
1869    }
1870
1871    @Override
1872    public boolean onCreateOptionsMenu(Menu menu) {
1873        super.onCreateOptionsMenu(menu);
1874
1875        if (mIsImageCaptureIntent) {
1876            // No options menu for attach mode.
1877            return false;
1878        } else {
1879            addBaseMenuItems(menu);
1880        }
1881        return true;
1882    }
1883
1884    private void addBaseMenuItems(Menu menu) {
1885        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
1886            public void run() {
1887                switchToOtherMode(ModePicker.MODE_VIDEO);
1888            }
1889        });
1890        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() {
1891            public void run() {
1892                switchToOtherMode(ModePicker.MODE_PANORAMA);
1893            }
1894        });
1895        MenuItem gallery = menu.add(R.string.camera_gallery_photos_text)
1896                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1897            public boolean onMenuItemClick(MenuItem item) {
1898                gotoGallery();
1899                return true;
1900            }
1901        });
1902        gallery.setIcon(android.R.drawable.ic_menu_gallery);
1903        mGalleryItems.add(gallery);
1904
1905        if (mNumberOfCameras > 1) {
1906            menu.add(R.string.switch_camera_id)
1907                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1908                public boolean onMenuItemClick(MenuItem item) {
1909                    CameraSettings.writePreferredCameraId(mPreferences,
1910                            ((mCameraId == mFrontCameraId)
1911                            ? mBackCameraId : mFrontCameraId));
1912                    onSharedPreferenceChanged();
1913                    return true;
1914                }
1915            }).setIcon(android.R.drawable.ic_menu_camera);
1916        }
1917    }
1918
1919    private boolean switchToOtherMode(int mode) {
1920        if (isFinishing() || !isCameraIdle()) return false;
1921        MenuHelper.gotoMode(mode, Camera.this);
1922        mHandler.removeMessages(FIRST_TIME_INIT);
1923        finish();
1924        return true;
1925    }
1926
1927    public boolean onModeChanged(int mode) {
1928        if (mode != ModePicker.MODE_CAMERA) {
1929            return switchToOtherMode(mode);
1930        } else {
1931            return true;
1932        }
1933    }
1934
1935    public void onSharedPreferenceChanged() {
1936        // ignore the events after "onPause()"
1937        if (mPausing) return;
1938
1939        boolean recordLocation;
1940
1941        recordLocation = RecordLocationPreference.get(
1942                mPreferences, getContentResolver());
1943
1944        if (mRecordLocation != recordLocation) {
1945            mRecordLocation = recordLocation;
1946            if (mRecordLocation) {
1947                mLocationManager.startReceivingLocationUpdates();
1948            } else {
1949                mLocationManager.stopReceivingLocationUpdates();
1950            }
1951        }
1952        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
1953        if (mCameraId != cameraId) {
1954            // Restart the activity to have a crossfade animation.
1955            // TODO: Use SurfaceTexture to implement a better and faster
1956            // animation.
1957            if (mIsImageCaptureIntent) {
1958                // If the intent is camera capture, stay in camera capture mode.
1959                MenuHelper.gotoCameraMode(this, getIntent());
1960            } else {
1961                MenuHelper.gotoCameraMode(this);
1962            }
1963
1964            finish();
1965        } else {
1966            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
1967        }
1968
1969        int exposureValue = CameraSettings.readExposure(mPreferences);
1970        updateExposureOnScreenIndicator(exposureValue);
1971    }
1972
1973    @Override
1974    public void onUserInteraction() {
1975        super.onUserInteraction();
1976        keepScreenOnAwhile();
1977    }
1978
1979    private void resetScreenOn() {
1980        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1981        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1982    }
1983
1984    private void keepScreenOnAwhile() {
1985        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1986        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1987        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1988    }
1989
1990    public void onRestorePreferencesClicked() {
1991        if (mPausing) return;
1992        Runnable runnable = new Runnable() {
1993            public void run() {
1994                restorePreferences();
1995            }
1996        };
1997        MenuHelper.confirmAction(this,
1998                getString(R.string.confirm_restore_title),
1999                getString(R.string.confirm_restore_message),
2000                runnable);
2001    }
2002
2003    private void restorePreferences() {
2004        // Reset the zoom. Zoom value is not stored in preference.
2005        if (mParameters.isZoomSupported()) {
2006            mZoomValue = 0;
2007            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
2008            mZoomControl.setZoomIndex(0);
2009        }
2010        if (mIndicatorControlContainer != null) {
2011            mIndicatorControlContainer.dismissSettingPopup();
2012            CameraSettings.restorePreferences(Camera.this, mPreferences,
2013                    mParameters);
2014            mIndicatorControlContainer.reloadPreferences();
2015            onSharedPreferenceChanged();
2016        }
2017    }
2018
2019    public void onOverriddenPreferencesClicked() {
2020        if (mPausing) return;
2021        if (mNotSelectableToast == null) {
2022            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
2023            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
2024        }
2025        mNotSelectableToast.show();
2026    }
2027
2028    private void showSharePopup() {
2029        Uri uri = mThumbnail.getUri();
2030        if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
2031            mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
2032                    mOrientationCompensation, mPreviewFrameLayout);
2033        }
2034        mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
2035    }
2036
2037    @Override
2038    public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
2039        mFaceView.setFaces(faces);
2040    }
2041
2042    private void showTapToFocusToast() {
2043        // Show the toast.
2044        RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt);
2045        v.setOrientation(mOrientationCompensation);
2046        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter));
2047        v.setVisibility(View.VISIBLE);
2048        mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000);
2049        // Clear the preference.
2050        Editor editor = mPreferences.edit();
2051        editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false);
2052        editor.apply();
2053    }
2054
2055    private void initializeCapabilities() {
2056        mInitialParams = mCameraDevice.getParameters();
2057        mFocusManager.initializeParameters(mInitialParams);
2058        mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0
2059                && isSupported(Parameters.FOCUS_MODE_AUTO,
2060                        mInitialParams.getSupportedFocusModes()));
2061        mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0);
2062    }
2063}
2064