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