Camera.java revision 5030bd7b700869feb50083571a680fa55730229b
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.gallery.IImage;
20import com.android.camera.gallery.IImageList;
21import com.android.camera.ui.CameraHeadUpDisplay;
22import com.android.camera.ui.CameraPicker;
23import com.android.camera.ui.ControlPanel;
24import com.android.camera.ui.FocusRectangle;
25import com.android.camera.ui.GLRootView;
26import com.android.camera.ui.HeadUpDisplay;
27import com.android.camera.ui.ZoomControllerListener;
28import com.android.camera.ui.ZoomPicker;
29
30import android.app.Activity;
31import android.content.ActivityNotFoundException;
32import android.content.BroadcastReceiver;
33import android.content.ContentProviderClient;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.SharedPreferences.Editor;
39import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
42import android.graphics.Bitmap;
43import android.graphics.BitmapFactory;
44import android.hardware.Camera.CameraInfo;
45import android.hardware.Camera.Parameters;
46import android.hardware.Camera.PictureCallback;
47import android.hardware.Camera.Size;
48import android.location.Location;
49import android.location.LocationManager;
50import android.location.LocationProvider;
51import android.media.AudioManager;
52import android.media.ToneGenerator;
53import android.net.Uri;
54import android.os.Build;
55import android.os.Bundle;
56import android.os.Environment;
57import android.os.Handler;
58import android.os.Looper;
59import android.os.Message;
60import android.os.MessageQueue;
61import android.provider.MediaStore;
62import android.provider.Settings;
63import android.provider.MediaStore.Images.ImageColumns;
64import android.provider.MediaStore.Images.Media;
65import android.util.Log;
66import android.view.GestureDetector;
67import android.view.KeyEvent;
68import android.view.LayoutInflater;
69import android.view.Menu;
70import android.view.MenuItem;
71import android.view.MotionEvent;
72import android.view.OrientationEventListener;
73import android.view.SurfaceHolder;
74import android.view.SurfaceView;
75import android.view.View;
76import android.view.ViewGroup;
77import android.view.ViewStub;
78import android.view.Window;
79import android.view.WindowManager;
80import android.view.MenuItem.OnMenuItemClickListener;
81
82import java.io.File;
83import java.io.FileNotFoundException;
84import java.io.FileOutputStream;
85import java.io.IOException;
86import java.io.OutputStream;
87import java.text.SimpleDateFormat;
88import java.util.ArrayList;
89import java.util.Collections;
90import java.util.Date;
91import java.util.HashMap;
92import java.util.List;
93
94/** The Camera activity which can preview and take pictures. */
95public class Camera extends NoSearchActivity implements View.OnClickListener,
96        ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
97        Switcher.OnSwitchListener {
98
99    private static final String TAG = "camera";
100
101    private static final int CROP_MSG = 1;
102    private static final int FIRST_TIME_INIT = 2;
103    private static final int RESTART_PREVIEW = 3;
104    private static final int CLEAR_SCREEN_DELAY = 4;
105    private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 5;
106
107    // The subset of parameters we need to update in setCameraParameters().
108    private static final int UPDATE_PARAM_INITIALIZE = 1;
109    private static final int UPDATE_PARAM_ZOOM = 2;
110    private static final int UPDATE_PARAM_PREFERENCE = 4;
111    private static final int UPDATE_PARAM_ALL = -1;
112
113    // When setCameraParametersWhenIdle() is called, we accumulate the subsets
114    // needed to be updated in mUpdateSet.
115    private int mUpdateSet;
116
117    // The brightness settings used when it is set to automatic in the system.
118    // The reason why it is set to 0.7 is just because 1.0 is too bright.
119    private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f;
120
121    private static final int SCREEN_DELAY = 2 * 60 * 1000;
122    private static final int FOCUS_BEEP_VOLUME = 100;
123
124    private static final int ZOOM_STOPPED = 0;
125    private static final int ZOOM_START = 1;
126    private static final int ZOOM_STOPPING = 2;
127
128    private int mZoomState = ZOOM_STOPPED;
129    private boolean mSmoothZoomSupported = false;
130    private int mZoomValue;  // The current zoom value.
131    private int mZoomMax;
132    private int mTargetZoomValue;
133    private ZoomPicker mZoomPicker;
134
135    private Parameters mParameters;
136    private Parameters mInitialParams;
137
138    private MyOrientationEventListener mOrientationListener;
139    // The device orientation in degrees. Default is unknown.
140    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
141    // The orientation compensation for icons and thumbnails.
142    private int mOrientationCompensation = 0;
143    private ComboPreferences mPreferences;
144
145    private static final int IDLE = 1;
146    private static final int SNAPSHOT_IN_PROGRESS = 2;
147
148    private static final boolean SWITCH_CAMERA = true;
149    private static final boolean SWITCH_VIDEO = false;
150
151    private int mStatus = IDLE;
152    private static final String sTempCropFilename = "crop-temp";
153
154    private android.hardware.Camera mCameraDevice;
155    private ContentProviderClient mMediaProviderClient;
156    private SurfaceView mSurfaceView;
157    private SurfaceHolder mSurfaceHolder = null;
158    private ShutterButton mShutterButton;
159    private FocusRectangle mFocusRectangle;
160    private ToneGenerator mFocusToneGenerator;
161    private GestureDetector mPopupGestureDetector;
162    private SwitcherSet mSwitcher;
163    private boolean mStartPreviewFail = false;
164    private View mIndicatorWheel;
165
166    private GLRootView mGLRootView;
167
168    // The last captured picture.
169    private RotateImageView mThumbnailButton;
170
171    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
172    private String mCropValue;
173    private Uri mSaveUri;
174
175    private ImageCapture mImageCapture = null;
176
177    // GPS on-screen indicator
178    private View mGpsNoSignalView;
179    private View mGpsHasSignalView;
180
181    // Front/Back camera pciker for xlarge layout
182    private CameraPicker mCameraPicker;
183
184    /**
185     * An unpublished intent flag requesting to return as soon as capturing
186     * is completed.
187     *
188     * TODO: consider publishing by moving into MediaStore.
189     */
190    private final static String EXTRA_QUICK_CAPTURE =
191            "android.intent.extra.quickCapture";
192
193    private boolean mPreviewing;
194    private boolean mPausing;
195    private boolean mFirstTimeInitialized;
196    private boolean mIsImageCaptureIntent;
197    private boolean mRecordLocation;
198
199    private static final int FOCUS_NOT_STARTED = 0;
200    private static final int FOCUSING = 1;
201    private static final int FOCUSING_SNAP_ON_FINISH = 2;
202    private static final int FOCUS_SUCCESS = 3;
203    private static final int FOCUS_FAIL = 4;
204    private int mFocusState = FOCUS_NOT_STARTED;
205
206    private ContentResolver mContentResolver;
207    private boolean mDidRegister = false;
208
209    private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
210
211    private LocationManager mLocationManager = null;
212
213    private final ShutterCallback mShutterCallback = new ShutterCallback();
214    private final PostViewPictureCallback mPostViewPictureCallback =
215            new PostViewPictureCallback();
216    private final RawPictureCallback mRawPictureCallback =
217            new RawPictureCallback();
218    private final AutoFocusCallback mAutoFocusCallback =
219            new AutoFocusCallback();
220    private final ZoomListener mZoomListener = new ZoomListener();
221    private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
222
223    private long mFocusStartTime;
224    private long mFocusCallbackTime;
225    private long mCaptureStartTime;
226    private long mShutterCallbackTime;
227    private long mPostViewPictureCallbackTime;
228    private long mRawPictureCallbackTime;
229    private long mJpegPictureCallbackTime;
230    private int mPicturesRemaining;
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    // Focus mode. Options are pref_camera_focusmode_entryvalues.
240    private String mFocusMode;
241    private String mSceneMode;
242
243    private final Handler mHandler = new MainHandler();
244    // xlarge devices use control panel. Other devices use head-up display.
245    private CameraHeadUpDisplay mHeadUpDisplay;
246    private ControlPanel mControlPanel;
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                    restartPreview();
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        }
294    }
295
296    private void resetExposureCompensation() {
297        String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
298                CameraSettings.EXPOSURE_DEFAULT_VALUE);
299        if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
300            Editor editor = mPreferences.edit();
301            editor.putString(CameraSettings.KEY_EXPOSURE, "0");
302            editor.apply();
303            if (mHeadUpDisplay != null) {
304                mHeadUpDisplay.reloadPreferences();
305            }
306        }
307    }
308
309    private void keepMediaProviderInstance() {
310        // We want to keep a reference to MediaProvider in camera's lifecycle.
311        // TODO: Utilize mMediaProviderClient instance to replace
312        // ContentResolver calls.
313        if (mMediaProviderClient == null) {
314            mMediaProviderClient = getContentResolver()
315                    .acquireContentProviderClient(MediaStore.AUTHORITY);
316        }
317    }
318
319    // Snapshots can only be taken after this is called. It should be called
320    // once only. We could have done these things in onCreate() but we want to
321    // make preview screen appear as soon as possible.
322    private void initializeFirstTime() {
323        if (mFirstTimeInitialized) return;
324
325        // Create orientation listenter. This should be done first because it
326        // takes some time to get first orientation.
327        mOrientationListener = new MyOrientationEventListener(Camera.this);
328        mOrientationListener.enable();
329
330        // Initialize location sevice.
331        mLocationManager = (LocationManager)
332                getSystemService(Context.LOCATION_SERVICE);
333        mRecordLocation = RecordLocationPreference.get(
334                mPreferences, getContentResolver());
335        initGpsOnScreenIndicator();
336        if (mRecordLocation) startReceivingLocationUpdates();
337
338        keepMediaProviderInstance();
339        checkStorage();
340
341        // Initialize last picture button.
342        mContentResolver = getContentResolver();
343        if (!mIsImageCaptureIntent)  {
344            findViewById(R.id.camera_switch).setOnClickListener(this);
345            initThumbnailButton();
346        }
347
348        // Initialize shutter button.
349        mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
350        mShutterButton.setOnShutterButtonListener(this);
351        mShutterButton.setVisibility(View.VISIBLE);
352
353        mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
354        updateFocusIndicator();
355
356        initializeScreenBrightness();
357        installIntentFilter();
358        initializeFocusTone();
359        initializeZoom();
360        // xlarge devices use control panel. Other devices use head-up display.
361        if (mControlPanel == null) {
362            mHeadUpDisplay = new CameraHeadUpDisplay(this);
363            mHeadUpDisplay.setListener(new MyHeadUpDisplayListener());
364            initializeHeadUpDisplay();
365        }
366        mFirstTimeInitialized = true;
367        changeHeadUpDisplayState();
368        addIdleHandler();
369    }
370
371    private void addIdleHandler() {
372        MessageQueue queue = Looper.myQueue();
373        queue.addIdleHandler(new MessageQueue.IdleHandler() {
374            public boolean queueIdle() {
375                ImageManager.ensureOSXCompatibleFolder();
376                return false;
377            }
378        });
379    }
380
381    private void initThumbnailButton() {
382        mThumbnailButton =
383                (RotateImageView) findViewById(R.id.review_thumbnail);
384        if (mThumbnailButton != null) {
385            mThumbnailButton.setOnClickListener(this);
386            mThumbnailButton.loadData(ImageManager.getLastImageThumbPath());
387            updateThumbnailButton();
388        }
389    }
390
391    private void updateThumbnailButton() {
392        if (mThumbnailButton == null) return;
393        // Update last image if URI is invalid and the storage is ready.
394        if (!mThumbnailButton.isUriValid() && mPicturesRemaining >= 0) {
395            IImageList list = ImageManager.makeImageList(
396                mContentResolver,
397                dataLocation(),
398                ImageManager.INCLUDE_IMAGES,
399                ImageManager.SORT_ASCENDING,
400                ImageManager.CAMERA_IMAGE_BUCKET_ID);
401            int count = list.getCount();
402            if (count > 0) {
403                IImage image = list.getImageAt(count - 1);
404                Uri uri = image.fullSizeImageUri();
405                mThumbnailButton.setData(uri, image.miniThumbBitmap());
406            } else {
407                mThumbnailButton.setData(null, null);
408            }
409            list.close();
410        }
411        mThumbnailButton.setVisibility(
412                (mThumbnailButton.getUri() != null) ? View.VISIBLE : View.GONE);
413    }
414
415    private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
416        if (mThumbnailButton == null) return;
417        BitmapFactory.Options options = new BitmapFactory.Options();
418        options.inSampleSize = 16;
419        Bitmap lastPictureThumb =
420                BitmapFactory.decodeByteArray(data, 0, data.length, options);
421        lastPictureThumb = Util.rotate(lastPictureThumb, degree);
422        mThumbnailButton.setData(uri, lastPictureThumb);
423        if (lastPictureThumb != null) {
424            mThumbnailButton.setVisibility(View.VISIBLE);
425        }
426    }
427
428    // If the activity is paused and resumed, this method will be called in
429    // onResume.
430    private void initializeSecondTime() {
431        // Start orientation listener as soon as possible because it takes
432        // some time to get first orientation.
433        mOrientationListener.enable();
434
435        // Start location update if needed.
436        mRecordLocation = RecordLocationPreference.get(
437                mPreferences, getContentResolver());
438        if (mRecordLocation) startReceivingLocationUpdates();
439
440        installIntentFilter();
441        initializeFocusTone();
442        initializeZoom();
443        changeHeadUpDisplayState();
444
445        keepMediaProviderInstance();
446        checkStorage();
447
448        if (!mIsImageCaptureIntent) {
449            updateThumbnailButton();
450        }
451    }
452
453    private void initializeZoom() {
454        if (!mParameters.isZoomSupported()) return;
455
456        mZoomMax = mParameters.getMaxZoom();
457        mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
458        if (mZoomPicker != null) {
459            mZoomPicker.setZoomRatios(getZoomRatios());
460            mZoomPicker.setZoomIndex(mParameters.getZoom());
461            mZoomPicker.setOnZoomChangeListener(
462                    new ZoomPicker.OnZoomChangedListener() {
463                public void onZoomChanged(int index) {
464                    onZoomValueChanged(index);
465                }
466            });
467        }
468
469        mCameraDevice.setZoomChangeListener(mZoomListener);
470    }
471
472    private void onZoomValueChanged(int index) {
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    private float[] getZoomRatios() {
492        if(!mParameters.isZoomSupported()) return null;
493        List<Integer> zoomRatios = mParameters.getZoomRatios();
494        float result[] = new float[zoomRatios.size()];
495        for (int i = 0, n = result.length; i < n; ++i) {
496            result[i] = (float) zoomRatios.get(i) / 100f;
497        }
498        return result;
499    }
500
501    private int mPopupLocations[] = new int[2];
502    private class PopupGestureListener extends
503            GestureDetector.SimpleOnGestureListener {
504        public boolean onDown(MotionEvent e) {
505            // Check if the popup window is visible.
506            View v = mControlPanel.getActivePopupWindow();
507            if (v == null) return false;
508
509            int x = Math.round(e.getX());
510            int y = Math.round(e.getY());
511
512            // Dismiss the popup window if users touch on the outside.
513            v.getLocationOnScreen(mPopupLocations);
514            if (x < mPopupLocations[0] || x > mPopupLocations[0] + v.getWidth()
515                    || y < mPopupLocations[1] || y > mPopupLocations[1] + v.getHeight()) {
516                mControlPanel.dismissSettingPopup();
517                // Let event fall through.
518            }
519            return false;
520        }
521    }
522
523    @Override
524    public boolean dispatchTouchEvent(MotionEvent m) {
525        // Check if the popup window should be dismissed first.
526        if (mPopupGestureDetector != null && mPopupGestureDetector.onTouchEvent(m)) {
527            return true;
528        }
529
530        return super.dispatchTouchEvent(m);
531    }
532
533    LocationListener [] mLocationListeners = new LocationListener[] {
534            new LocationListener(LocationManager.GPS_PROVIDER),
535            new LocationListener(LocationManager.NETWORK_PROVIDER)
536    };
537
538    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
539        @Override
540        public void onReceive(Context context, Intent intent) {
541            String action = intent.getAction();
542            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
543                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
544                    || action.equals(Intent.ACTION_MEDIA_CHECKING)) {
545                checkStorage();
546            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
547                checkStorage();
548                if (!mIsImageCaptureIntent)  {
549                    updateThumbnailButton();
550                }
551            }
552        }
553    };
554
555    private void initializeCameraPicker() {
556        mCameraPicker = (CameraPicker) findViewById(R.id.camera_picker);
557        if (mCameraPicker != null) {
558            mCameraPicker.setImageResource(R.drawable.camera_toggle);
559            ListPreference pref = mPreferenceGroup.findPreference(
560                    CameraSettings.KEY_CAMERA_ID);
561            if (pref != null) {
562                mCameraPicker.initialize(pref);
563                mCameraPicker.setListener(new MyCameraPickerListener());
564            }
565        }
566    }
567
568    private void initGpsOnScreenIndicator() {
569        mGpsNoSignalView = findViewById(R.id.onscreen_gps_indicator_no_signal);
570        mGpsHasSignalView = findViewById(R.id.onscreen_gps_indicator_on);
571    }
572
573    private void showGpsOnScreenIndicator(boolean hasSignal) {
574        if (hasSignal) {
575            if (mGpsNoSignalView != null) mGpsNoSignalView.setVisibility(View.INVISIBLE);
576            if (mGpsHasSignalView != null) mGpsHasSignalView.setVisibility(View.VISIBLE);
577        } else {
578            if (mGpsNoSignalView != null) mGpsNoSignalView.setVisibility(View.VISIBLE);
579            if (mGpsHasSignalView != null) mGpsHasSignalView.setVisibility(View.INVISIBLE);
580        }
581    }
582
583    private void hideGpsOnScreenIndicator() {
584        if (mGpsNoSignalView != null) mGpsNoSignalView.setVisibility(View.INVISIBLE);
585        if (mGpsHasSignalView != null) mGpsHasSignalView.setVisibility(View.INVISIBLE);
586    }
587
588    private class LocationListener
589            implements android.location.LocationListener {
590        Location mLastLocation;
591        boolean mValid = false;
592        String mProvider;
593
594        public LocationListener(String provider) {
595            mProvider = provider;
596            mLastLocation = new Location(mProvider);
597        }
598
599        public void onLocationChanged(Location newLocation) {
600            if (newLocation.getLatitude() == 0.0
601                    && newLocation.getLongitude() == 0.0) {
602                // Hack to filter out 0.0,0.0 locations
603                return;
604            }
605            // If GPS is available before start camera, we won't get status
606            // update so update GPS indicator when we receive data.
607            if (mRecordLocation
608                    && LocationManager.GPS_PROVIDER.equals(mProvider)) {
609                if (mHeadUpDisplay != null) {
610                    mHeadUpDisplay.setGpsHasSignal(true);
611                }
612                showGpsOnScreenIndicator(true);
613            }
614            mLastLocation.set(newLocation);
615            mValid = true;
616        }
617
618        public void onProviderEnabled(String provider) {
619        }
620
621        public void onProviderDisabled(String provider) {
622            mValid = false;
623        }
624
625        public void onStatusChanged(
626                String provider, int status, Bundle extras) {
627            switch(status) {
628                case LocationProvider.OUT_OF_SERVICE:
629                case LocationProvider.TEMPORARILY_UNAVAILABLE: {
630                    mValid = false;
631                    if (mRecordLocation &&
632                            LocationManager.GPS_PROVIDER.equals(provider)) {
633                        if (mHeadUpDisplay != null) {
634                            mHeadUpDisplay.setGpsHasSignal(false);
635                        }
636                        showGpsOnScreenIndicator(false);
637                    }
638                    break;
639                }
640            }
641        }
642
643        public Location current() {
644            return mValid ? mLastLocation : null;
645        }
646    }
647
648    private final class ShutterCallback
649            implements android.hardware.Camera.ShutterCallback {
650        public void onShutter() {
651            mShutterCallbackTime = System.currentTimeMillis();
652            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
653            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
654            clearFocusState();
655        }
656    }
657
658    private final class PostViewPictureCallback implements PictureCallback {
659        public void onPictureTaken(
660                byte [] data, android.hardware.Camera camera) {
661            mPostViewPictureCallbackTime = System.currentTimeMillis();
662            Log.v(TAG, "mShutterToPostViewCallbackTime = "
663                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
664                    + "ms");
665        }
666    }
667
668    private final class RawPictureCallback implements PictureCallback {
669        public void onPictureTaken(
670                byte [] rawData, android.hardware.Camera camera) {
671            mRawPictureCallbackTime = System.currentTimeMillis();
672            Log.v(TAG, "mShutterToRawCallbackTime = "
673                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
674        }
675    }
676
677    private final class JpegPictureCallback implements PictureCallback {
678        Location mLocation;
679
680        public JpegPictureCallback(Location loc) {
681            mLocation = loc;
682        }
683
684        public void onPictureTaken(
685                final byte [] jpegData, final android.hardware.Camera camera) {
686            if (mPausing) {
687                return;
688            }
689
690            mJpegPictureCallbackTime = System.currentTimeMillis();
691            // If postview callback has arrived, the captured image is displayed
692            // in postview callback. If not, the captured image is displayed in
693            // raw picture callback.
694            if (mPostViewPictureCallbackTime != 0) {
695                mShutterToPictureDisplayedTime =
696                        mPostViewPictureCallbackTime - mShutterCallbackTime;
697                mPictureDisplayedToJpegCallbackTime =
698                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
699            } else {
700                mShutterToPictureDisplayedTime =
701                        mRawPictureCallbackTime - mShutterCallbackTime;
702                mPictureDisplayedToJpegCallbackTime =
703                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
704            }
705            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
706                    + mPictureDisplayedToJpegCallbackTime + "ms");
707            enableCameraControls(true);
708
709            if (!mIsImageCaptureIntent) {
710                // We want to show the taken picture for a while, so we wait
711                // for at least 1.2 second before restarting the preview.
712                long delay = 1200 - mPictureDisplayedToJpegCallbackTime;
713                if (delay < 0) {
714                    restartPreview();
715                } else {
716                    mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
717                }
718            }
719            mImageCapture.storeImage(jpegData, camera, mLocation);
720
721            // Calculate this in advance of each shot so we don't add to shutter
722            // latency. It's true that someone else could write to the SD card in
723            // the mean time and fill it, but that could have happened between the
724            // shutter press and saving the JPEG too.
725            calculatePicturesRemaining();
726
727            if (mPicturesRemaining < 1) {
728                updateStorageHint(mPicturesRemaining);
729            }
730
731            if (!mHandler.hasMessages(RESTART_PREVIEW)) {
732                long now = System.currentTimeMillis();
733                mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
734                Log.v(TAG, "mJpegCallbackFinishTime = "
735                        + mJpegCallbackFinishTime + "ms");
736                mJpegPictureCallbackTime = 0;
737            }
738        }
739    }
740
741    private final class AutoFocusCallback
742            implements android.hardware.Camera.AutoFocusCallback {
743        public void onAutoFocus(
744                boolean focused, android.hardware.Camera camera) {
745            mFocusCallbackTime = System.currentTimeMillis();
746            mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
747            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
748            if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
749                // Take the picture no matter focus succeeds or fails. No need
750                // to play the AF sound if we're about to play the shutter
751                // sound.
752                if (focused) {
753                    mFocusState = FOCUS_SUCCESS;
754                } else {
755                    mFocusState = FOCUS_FAIL;
756                }
757                mImageCapture.onSnap();
758            } else if (mFocusState == FOCUSING) {
759                // User is half-pressing the focus key. Play the focus tone.
760                // Do not take the picture now.
761                ToneGenerator tg = mFocusToneGenerator;
762                if (tg != null) {
763                    tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
764                }
765                if (focused) {
766                    mFocusState = FOCUS_SUCCESS;
767                } else {
768                    mFocusState = FOCUS_FAIL;
769                }
770            } else if (mFocusState == FOCUS_NOT_STARTED) {
771                // User has released the focus key before focus completes.
772                // Do nothing.
773            }
774            updateFocusIndicator();
775        }
776    }
777
778    private final class ZoomListener
779            implements android.hardware.Camera.OnZoomChangeListener {
780        public void onZoomChange(
781                int value, boolean stopped, android.hardware.Camera camera) {
782            Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
783            mZoomValue = value;
784            // Keep mParameters up to date. We do not getParameter again in
785            // takePicture. If we do not do this, wrong zoom value will be set.
786            mParameters.setZoom(value);
787            // We only care if the zoom is stopped. mZooming is set to true when
788            // we start smooth zoom.
789            if (stopped && mZoomState != ZOOM_STOPPED) {
790                if (value != mTargetZoomValue) {
791                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
792                    mZoomState = ZOOM_START;
793                } else {
794                    mZoomState = ZOOM_STOPPED;
795                }
796            }
797        }
798    }
799
800    private class ImageCapture {
801
802        private Uri mLastContentUri;
803
804        byte[] mCaptureOnlyData;
805
806        // Returns the rotation degree in the jpeg header.
807        private int storeImage(byte[] data, Location loc) {
808            try {
809                long dateTaken = System.currentTimeMillis();
810                String title = createName(dateTaken);
811                String filename = title + ".jpg";
812                int[] degree = new int[1];
813                mLastContentUri = ImageManager.addImage(
814                        mContentResolver,
815                        title,
816                        dateTaken,
817                        loc, // location from gps/network
818                        ImageManager.CAMERA_IMAGE_BUCKET_NAME, filename,
819                        null, data,
820                        degree);
821                return degree[0];
822            } catch (Exception ex) {
823                Log.e(TAG, "Exception while compressing image.", ex);
824                return 0;
825            }
826        }
827
828        public void storeImage(final byte[] data,
829                android.hardware.Camera camera, Location loc) {
830            if (!mIsImageCaptureIntent) {
831                int degree = storeImage(data, loc);
832                sendBroadcast(new Intent(
833                        "com.android.camera.NEW_PICTURE", mLastContentUri));
834                setLastPictureThumb(data, degree,
835                        mImageCapture.getLastCaptureUri());
836            } else {
837                mCaptureOnlyData = data;
838                if (!mQuickCapture) {
839                    showPostCaptureAlert();
840                } else {
841                    doAttach();
842                }
843            }
844        }
845
846        /**
847         * Initiate the capture of an image.
848         */
849        public void initiate() {
850            if (mCameraDevice == null) {
851                return;
852            }
853
854            capture();
855        }
856
857        public Uri getLastCaptureUri() {
858            return mLastContentUri;
859        }
860
861        public byte[] getLastCaptureData() {
862            return mCaptureOnlyData;
863        }
864
865        private void capture() {
866            mCaptureOnlyData = null;
867
868            // See android.hardware.Camera.Parameters.setRotation for
869            // documentation.
870            int rotation = 0;
871            if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
872                CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
873                if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
874                    rotation = (info.orientation - mOrientation + 360) % 360;
875                } else {  // back-facing camera
876                    rotation = (info.orientation + mOrientation) % 360;
877                }
878            }
879            mParameters.setRotation(rotation);
880
881            // Clear previous GPS location from the parameters.
882            mParameters.removeGpsData();
883
884            // We always encode GpsTimeStamp
885            mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
886
887            // Set GPS location.
888            Location loc = mRecordLocation ? getCurrentLocation() : null;
889            if (loc != null) {
890                double lat = loc.getLatitude();
891                double lon = loc.getLongitude();
892                boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
893
894                if (hasLatLon) {
895                    mParameters.setGpsLatitude(lat);
896                    mParameters.setGpsLongitude(lon);
897                    mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
898                    if (loc.hasAltitude()) {
899                        mParameters.setGpsAltitude(loc.getAltitude());
900                    } else {
901                        // for NETWORK_PROVIDER location provider, we may have
902                        // no altitude information, but the driver needs it, so
903                        // we fake one.
904                        mParameters.setGpsAltitude(0);
905                    }
906                    if (loc.getTime() != 0) {
907                        // Location.getTime() is UTC in milliseconds.
908                        // gps-timestamp is UTC in seconds.
909                        long utcTimeSeconds = loc.getTime() / 1000;
910                        mParameters.setGpsTimestamp(utcTimeSeconds);
911                    }
912                } else {
913                    loc = null;
914                }
915            }
916
917            mCameraDevice.setParameters(mParameters);
918
919            mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
920                    mPostViewPictureCallback, new JpegPictureCallback(loc));
921            mPreviewing = false;
922        }
923
924        public void onSnap() {
925            // If we are already in the middle of taking a snapshot then ignore.
926            if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
927                return;
928            }
929            mCaptureStartTime = System.currentTimeMillis();
930            mPostViewPictureCallbackTime = 0;
931            enableCameraControls(false);
932            mStatus = SNAPSHOT_IN_PROGRESS;
933
934            mImageCapture.initiate();
935        }
936
937        private void clearLastData() {
938            mCaptureOnlyData = null;
939        }
940    }
941
942    private boolean saveDataToFile(String filePath, byte[] data) {
943        FileOutputStream f = null;
944        try {
945            f = new FileOutputStream(filePath);
946            f.write(data);
947        } catch (IOException e) {
948            return false;
949        } finally {
950            MenuHelper.closeSilently(f);
951        }
952        return true;
953    }
954
955    private String createName(long dateTaken) {
956        Date date = new Date(dateTaken);
957        SimpleDateFormat dateFormat = new SimpleDateFormat(
958                getString(R.string.image_file_name_format));
959
960        return dateFormat.format(date);
961    }
962
963    @Override
964    public void onCreate(Bundle icicle) {
965        super.onCreate(icicle);
966
967        mIsImageCaptureIntent = isImageCaptureIntent();
968        if (mIsImageCaptureIntent) {
969            setContentView(R.layout.camera_attach);
970        } else {
971            setContentView(R.layout.camera);
972        }
973        mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview);
974
975        mPreferences = new ComboPreferences(this);
976        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
977        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
978        mPreferences.setLocalId(this, mCameraId);
979        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
980
981        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
982        mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
983
984        // we need to reset exposure for the preview
985        resetExposureCompensation();
986        /*
987         * To reduce startup time, we start the preview in another thread.
988         * We make sure the preview is started at the end of onCreate.
989         */
990        Thread startPreviewThread = new Thread(new Runnable() {
991            public void run() {
992                try {
993                    mStartPreviewFail = false;
994                    startPreview();
995                } catch (CameraHardwareException e) {
996                    // In eng build, we throw the exception so that test tool
997                    // can detect it and report it
998                    if ("eng".equals(Build.TYPE)) {
999                        throw new RuntimeException(e);
1000                    }
1001                    mStartPreviewFail = true;
1002                }
1003            }
1004        });
1005        startPreviewThread.start();
1006
1007        // don't set mSurfaceHolder here. We have it set ONLY within
1008        // surfaceChanged / surfaceDestroyed, other parts of the code
1009        // assume that when it is set, the surface is also set.
1010        SurfaceHolder holder = mSurfaceView.getHolder();
1011        holder.addCallback(this);
1012        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
1013
1014        if (mIsImageCaptureIntent) {
1015            setupCaptureParams();
1016
1017            View reviewControl = findViewById(R.id.review_control);
1018            reviewControl.setVisibility(View.VISIBLE);
1019            reviewControl.findViewById(R.id.btn_cancel).setOnClickListener(this);
1020            reviewControl.findViewById(R.id.btn_retake).setOnClickListener(this);
1021            reviewControl.findViewById(R.id.btn_done).setOnClickListener(this);
1022        } else {
1023            mSwitcher = (SwitcherSet) findViewById(R.id.camera_switch);
1024            mSwitcher.setVisibility(View.VISIBLE);
1025            mSwitcher.setOnSwitchListener(this);
1026        }
1027        mIndicatorWheel = findViewById(R.id.indicator_wheel);
1028
1029        // Make sure preview is started.
1030        try {
1031            startPreviewThread.join();
1032            if (mStartPreviewFail) {
1033                showCameraErrorAndFinish();
1034                return;
1035            }
1036        } catch (InterruptedException ex) {
1037            // ignore
1038        }
1039
1040        // Do this after starting preview because it depends on camera
1041        // parameters.
1042        initializeControlPanel();
1043        initializeCameraPicker();
1044
1045        if (mControlPanel != null) {
1046            mZoomPicker = (ZoomPicker) mControlPanel.findViewById(R.id.zoom_picker);
1047            mZoomPicker.setEnabled(true); // disabled initially in xml
1048        }
1049    }
1050
1051    private void changeHeadUpDisplayState() {
1052        if (mHeadUpDisplay == null) return;
1053        // If the camera resumes behind the lock screen, the orientation
1054        // will be portrait. That causes OOM when we try to allocation GPU
1055        // memory for the GLSurfaceView again when the orientation changes. So,
1056        // we delayed initialization of HeadUpDisplay until the orientation
1057        // becomes landscape.
1058        Configuration config = getResources().getConfiguration();
1059        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
1060                && !mPausing && mFirstTimeInitialized) {
1061            if (mGLRootView == null) attachHeadUpDisplay();
1062        } else if (mGLRootView != null) {
1063            detachHeadUpDisplay();
1064        }
1065    }
1066
1067    private void overrideCameraSettings(final String flashMode,
1068            final String whiteBalance, final String focusMode) {
1069        if (mHeadUpDisplay != null) {
1070            mHeadUpDisplay.overrideSettings(
1071                    CameraSettings.KEY_FLASH_MODE, flashMode,
1072                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
1073                    CameraSettings.KEY_FOCUS_MODE, focusMode);
1074        }
1075        if (mControlPanel != null) {
1076            mControlPanel.overrideSettings(
1077                    CameraSettings.KEY_FLASH_MODE, flashMode,
1078                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
1079                    CameraSettings.KEY_FOCUS_MODE, focusMode);
1080        }
1081    }
1082
1083    private void updateSceneModeUI() {
1084        // If scene mode is set, we cannot set flash mode, white balance, and
1085        // focus mode, instead, we read it from driver
1086        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1087            overrideCameraSettings(mParameters.getFlashMode(),
1088                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
1089        } else {
1090            overrideCameraSettings(null, null, null);
1091        }
1092    }
1093
1094    private void loadCameraPreferences() {
1095        CameraSettings settings = new CameraSettings(this, mInitialParams,
1096                mCameraId, CameraHolder.instance().getCameraInfo());
1097        // Only need to load camera IDs once
1098        if (mPreferenceGroup == null) {
1099            mPreferenceGroup = settings.getPreferenceGroup(
1100                    R.xml.camera_preferences);
1101            mFrontCameraId =
1102                    settings.getCameraIdByIndex(CameraInfo.CAMERA_FACING_FRONT);
1103            mBackCameraId =
1104                    settings.getCameraIdByIndex(CameraInfo.CAMERA_FACING_BACK);
1105        } else {
1106            mPreferenceGroup = settings.getPreferenceGroup(
1107                    R.xml.camera_preferences);
1108        }
1109    }
1110
1111    private void initializeControlPanel() {
1112        mControlPanel = (ControlPanel) findViewById(R.id.control_panel);
1113        if (mControlPanel == null) return;
1114        loadCameraPreferences();
1115
1116        String[] keys = new String[]{CameraSettings.KEY_FLASH_MODE,
1117            CameraSettings.KEY_WHITE_BALANCE,
1118            CameraSettings.KEY_COLOR_EFFECT,
1119            CameraSettings.KEY_SCENE_MODE};
1120        mControlPanel.initialize(this, mPreferenceGroup, keys, true);
1121        mControlPanel.setListener(new MyControlPanelListener());
1122        mPopupGestureDetector = new GestureDetector(this,
1123                new PopupGestureListener());
1124        updateSceneModeUI();
1125    }
1126
1127    private void initializeHeadUpDisplay() {
1128        if (mHeadUpDisplay == null) return;
1129        loadCameraPreferences();
1130
1131        // If we have zoom picker, do not show zoom control on head-up display.
1132        float[] zoomRatios = null;
1133        if (mZoomPicker == null) zoomRatios = getZoomRatios();
1134        mHeadUpDisplay.initialize(this, mPreferenceGroup,
1135                zoomRatios, mOrientationCompensation);
1136        if (mZoomPicker == null && mParameters.isZoomSupported()) {
1137            mHeadUpDisplay.setZoomListener(new ZoomControllerListener() {
1138                public void onZoomChanged(
1139                        int index, float ratio, boolean isMoving) {
1140                    onZoomValueChanged(index);
1141                }
1142            });
1143        }
1144        updateSceneModeUI();
1145    }
1146
1147    private void attachHeadUpDisplay() {
1148        mHeadUpDisplay.setOrientation(mOrientationCompensation);
1149        if (mParameters.isZoomSupported()) {
1150            mHeadUpDisplay.setZoomIndex(mZoomValue);
1151        }
1152        ViewGroup frame = (ViewGroup) findViewById(R.id.frame);
1153        mGLRootView = new GLRootView(this);
1154        mGLRootView.setContentPane(mHeadUpDisplay);
1155        frame.addView(mGLRootView);
1156    }
1157
1158    private void detachHeadUpDisplay() {
1159        mHeadUpDisplay.setGpsHasSignal(false);
1160        mHeadUpDisplay.collapse();
1161        ((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView);
1162        mGLRootView = null;
1163    }
1164
1165    private boolean collapseCameraControls() {
1166        if (mHeadUpDisplay != null && mHeadUpDisplay.collapse()) {
1167            return true;
1168        }
1169        if (mControlPanel != null && mControlPanel.dismissSettingPopup()) {
1170            return true;
1171        }
1172        return false;
1173    }
1174
1175    private void enableCameraControls(boolean enable) {
1176        if (mHeadUpDisplay != null) mHeadUpDisplay.setEnabled(enable);
1177        if (mControlPanel != null) mControlPanel.setEnabled(enable);
1178    }
1179
1180    public static int roundOrientation(int orientation) {
1181        return ((orientation + 45) / 90 * 90) % 360;
1182    }
1183
1184    private class MyOrientationEventListener
1185            extends OrientationEventListener {
1186        public MyOrientationEventListener(Context context) {
1187            super(context);
1188        }
1189
1190        @Override
1191        public void onOrientationChanged(int orientation) {
1192            // We keep the last known orientation. So if the user first orient
1193            // the camera then point the camera to floor or sky, we still have
1194            // the correct orientation.
1195            if (orientation == ORIENTATION_UNKNOWN) return;
1196            mOrientation = roundOrientation(orientation);
1197            // When the screen is unlocked, display rotation may change. Always
1198            // calculate the up-to-date orientationCompensation.
1199            int orientationCompensation = mOrientation
1200                    + Util.getDisplayRotation(Camera.this);
1201            if (mOrientationCompensation != orientationCompensation) {
1202                mOrientationCompensation = orientationCompensation;
1203                if (!mIsImageCaptureIntent) {
1204                    setOrientationIndicator(mOrientationCompensation);
1205                }
1206                if (mHeadUpDisplay != null) {
1207                    mHeadUpDisplay.setOrientation(mOrientationCompensation);
1208                }
1209            }
1210        }
1211    }
1212
1213    private void setOrientationIndicator(int degree) {
1214        RotateImageView icon = (RotateImageView) findViewById(
1215                R.id.review_thumbnail);
1216        if (icon != null) icon.setDegree(degree);
1217
1218        icon = (RotateImageView) findViewById(R.id.camera_switch_icon);
1219        if (icon != null) icon.setDegree(degree);
1220        icon = (RotateImageView) findViewById(R.id.video_switch_icon);
1221        if (icon != null) icon.setDegree(degree);
1222    }
1223
1224    @Override
1225    public void onStart() {
1226        super.onStart();
1227        if (!mIsImageCaptureIntent) {
1228            mSwitcher.setSwitch(SWITCH_CAMERA);
1229        }
1230    }
1231
1232    @Override
1233    public void onStop() {
1234        super.onStop();
1235        if (mMediaProviderClient != null) {
1236            mMediaProviderClient.release();
1237            mMediaProviderClient = null;
1238        }
1239    }
1240
1241    private void checkStorage() {
1242        calculatePicturesRemaining();
1243        updateStorageHint(mPicturesRemaining);
1244    }
1245
1246    public void onClick(View v) {
1247        switch (v.getId()) {
1248            case R.id.btn_retake:
1249                hidePostCaptureAlert();
1250                restartPreview();
1251                break;
1252            case R.id.review_thumbnail:
1253                if (isCameraIdle()) {
1254                    viewImage(mThumbnailButton);
1255                }
1256                break;
1257            case R.id.btn_done:
1258                doAttach();
1259                break;
1260            case R.id.btn_cancel:
1261                doCancel();
1262                break;
1263            case R.id.btn_gallery:
1264                gotoGallery();
1265                break;
1266        }
1267    }
1268
1269    private Bitmap createCaptureBitmap(byte[] data) {
1270        // This is really stupid...we just want to read the orientation in
1271        // the jpeg header.
1272        String filepath = ImageManager.getTempJpegPath();
1273        int degree = 0;
1274        if (saveDataToFile(filepath, data)) {
1275            degree = ImageManager.getExifOrientation(filepath);
1276            new File(filepath).delete();
1277        }
1278
1279        // Limit to 50k pixels so we can return it in the intent.
1280        Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1281        bitmap = Util.rotate(bitmap, degree);
1282        return bitmap;
1283    }
1284
1285    private void doAttach() {
1286        if (mPausing) {
1287            return;
1288        }
1289
1290        byte[] data = mImageCapture.getLastCaptureData();
1291
1292        if (mCropValue == null) {
1293            // First handle the no crop case -- just return the value.  If the
1294            // caller specifies a "save uri" then write the data to it's
1295            // stream. Otherwise, pass back a scaled down version of the bitmap
1296            // directly in the extras.
1297            if (mSaveUri != null) {
1298                OutputStream outputStream = null;
1299                try {
1300                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1301                    outputStream.write(data);
1302                    outputStream.close();
1303
1304                    setResult(RESULT_OK);
1305                    finish();
1306                } catch (IOException ex) {
1307                    // ignore exception
1308                } finally {
1309                    Util.closeSilently(outputStream);
1310                }
1311            } else {
1312                Bitmap bitmap = createCaptureBitmap(data);
1313                setResult(RESULT_OK,
1314                        new Intent("inline-data").putExtra("data", bitmap));
1315                finish();
1316            }
1317        } else {
1318            // Save the image to a temp file and invoke the cropper
1319            Uri tempUri = null;
1320            FileOutputStream tempStream = null;
1321            try {
1322                File path = getFileStreamPath(sTempCropFilename);
1323                path.delete();
1324                tempStream = openFileOutput(sTempCropFilename, 0);
1325                tempStream.write(data);
1326                tempStream.close();
1327                tempUri = Uri.fromFile(path);
1328            } catch (FileNotFoundException ex) {
1329                setResult(Activity.RESULT_CANCELED);
1330                finish();
1331                return;
1332            } catch (IOException ex) {
1333                setResult(Activity.RESULT_CANCELED);
1334                finish();
1335                return;
1336            } finally {
1337                Util.closeSilently(tempStream);
1338            }
1339
1340            Bundle newExtras = new Bundle();
1341            if (mCropValue.equals("circle")) {
1342                newExtras.putString("circleCrop", "true");
1343            }
1344            if (mSaveUri != null) {
1345                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1346            } else {
1347                newExtras.putBoolean("return-data", true);
1348            }
1349
1350            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1351
1352            cropIntent.setData(tempUri);
1353            cropIntent.putExtras(newExtras);
1354
1355            startActivityForResult(cropIntent, CROP_MSG);
1356        }
1357    }
1358
1359    private void doCancel() {
1360        setResult(RESULT_CANCELED, new Intent());
1361        finish();
1362    }
1363
1364    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1365        if (mPausing) {
1366            return;
1367        }
1368        switch (button.getId()) {
1369            case R.id.shutter_button:
1370                doFocus(pressed);
1371                break;
1372        }
1373    }
1374
1375    public void onShutterButtonClick(ShutterButton button) {
1376        if (mPausing) {
1377            return;
1378        }
1379        switch (button.getId()) {
1380            case R.id.shutter_button:
1381                doSnap();
1382                break;
1383        }
1384    }
1385
1386    private OnScreenHint mStorageHint;
1387
1388    private void updateStorageHint(int remaining) {
1389        String noStorageText = null;
1390
1391        if (remaining == MenuHelper.NO_STORAGE_ERROR) {
1392            String state = Environment.getExternalStorageState();
1393            if (state == Environment.MEDIA_CHECKING) {
1394                noStorageText = getString(R.string.preparing_sd);
1395            } else {
1396                noStorageText = getString(R.string.no_storage);
1397            }
1398        } else if (remaining == MenuHelper.CANNOT_STAT_ERROR) {
1399            noStorageText = getString(R.string.access_sd_fail);
1400        } else if (remaining < 1) {
1401            noStorageText = getString(R.string.not_enough_space);
1402        }
1403
1404        if (noStorageText != null) {
1405            if (mStorageHint == null) {
1406                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1407            } else {
1408                mStorageHint.setText(noStorageText);
1409            }
1410            mStorageHint.show();
1411        } else if (mStorageHint != null) {
1412            mStorageHint.cancel();
1413            mStorageHint = null;
1414        }
1415    }
1416
1417    private void installIntentFilter() {
1418        // install an intent filter to receive SD card related events.
1419        IntentFilter intentFilter =
1420                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1421        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1422        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1423        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1424        intentFilter.addDataScheme("file");
1425        registerReceiver(mReceiver, intentFilter);
1426        mDidRegister = true;
1427    }
1428
1429    private void initializeFocusTone() {
1430        // Initialize focus tone generator.
1431        try {
1432            mFocusToneGenerator = new ToneGenerator(
1433                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1434        } catch (Throwable ex) {
1435            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1436            mFocusToneGenerator = null;
1437        }
1438    }
1439
1440    private void initializeScreenBrightness() {
1441        Window win = getWindow();
1442        // Overright the brightness settings if it is automatic
1443        int mode = Settings.System.getInt(
1444                getContentResolver(),
1445                Settings.System.SCREEN_BRIGHTNESS_MODE,
1446                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1447        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1448            WindowManager.LayoutParams winParams = win.getAttributes();
1449            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1450            win.setAttributes(winParams);
1451        }
1452    }
1453
1454    @Override
1455    protected void onResume() {
1456        super.onResume();
1457
1458        mPausing = false;
1459        mJpegPictureCallbackTime = 0;
1460        mZoomValue = 0;
1461        mImageCapture = new ImageCapture();
1462
1463        // Start the preview if it is not started.
1464        if (!mPreviewing && !mStartPreviewFail) {
1465            resetExposureCompensation();
1466            if (!restartPreview()) return;
1467        }
1468
1469        if (mSurfaceHolder != null) {
1470            // If first time initialization is not finished, put it in the
1471            // message queue.
1472            if (!mFirstTimeInitialized) {
1473                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1474            } else {
1475                initializeSecondTime();
1476            }
1477        }
1478        keepScreenOnAwhile();
1479    }
1480
1481    @Override
1482    public void onConfigurationChanged(Configuration config) {
1483        super.onConfigurationChanged(config);
1484        changeHeadUpDisplayState();
1485    }
1486
1487    private static ImageManager.DataLocation dataLocation() {
1488        return ImageManager.DataLocation.EXTERNAL;
1489    }
1490
1491    @Override
1492    protected void onPause() {
1493        mPausing = true;
1494        stopPreview();
1495        // Close the camera now because other activities may need to use it.
1496        closeCamera();
1497        resetScreenOn();
1498        collapseCameraControls();
1499        changeHeadUpDisplayState();
1500
1501        if (mFirstTimeInitialized) {
1502            mOrientationListener.disable();
1503            if (!mIsImageCaptureIntent) {
1504                if (mThumbnailButton != null) {
1505                    mThumbnailButton.storeData(
1506                            ImageManager.getLastImageThumbPath());
1507                }
1508            }
1509            hidePostCaptureAlert();
1510        }
1511
1512        if (mDidRegister) {
1513            unregisterReceiver(mReceiver);
1514            mDidRegister = false;
1515        }
1516        stopReceivingLocationUpdates();
1517
1518        if (mFocusToneGenerator != null) {
1519            mFocusToneGenerator.release();
1520            mFocusToneGenerator = null;
1521        }
1522
1523        if (mStorageHint != null) {
1524            mStorageHint.cancel();
1525            mStorageHint = null;
1526        }
1527
1528        // If we are in an image capture intent and has taken
1529        // a picture, we just clear it in onPause.
1530        mImageCapture.clearLastData();
1531        mImageCapture = null;
1532
1533        // Remove the messages in the event queue.
1534        mHandler.removeMessages(RESTART_PREVIEW);
1535        mHandler.removeMessages(FIRST_TIME_INIT);
1536
1537        super.onPause();
1538    }
1539
1540    @Override
1541    protected void onActivityResult(
1542            int requestCode, int resultCode, Intent data) {
1543        switch (requestCode) {
1544            case CROP_MSG: {
1545                Intent intent = new Intent();
1546                if (data != null) {
1547                    Bundle extras = data.getExtras();
1548                    if (extras != null) {
1549                        intent.putExtras(extras);
1550                    }
1551                }
1552                setResult(resultCode, intent);
1553                finish();
1554
1555                File path = getFileStreamPath(sTempCropFilename);
1556                path.delete();
1557
1558                break;
1559            }
1560        }
1561    }
1562
1563    private boolean canTakePicture() {
1564        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1565    }
1566
1567    private void autoFocus() {
1568        // Initiate autofocus only when preview is started and snapshot is not
1569        // in progress.
1570        if (canTakePicture()) {
1571            enableCameraControls(false);
1572            Log.v(TAG, "Start autofocus.");
1573            mFocusStartTime = System.currentTimeMillis();
1574            mFocusState = FOCUSING;
1575            updateFocusIndicator();
1576            mCameraDevice.autoFocus(mAutoFocusCallback);
1577        }
1578    }
1579
1580    private void cancelAutoFocus() {
1581        // User releases half-pressed focus key.
1582        if (mStatus != SNAPSHOT_IN_PROGRESS && (mFocusState == FOCUSING
1583                || mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) {
1584            Log.v(TAG, "Cancel autofocus.");
1585            enableCameraControls(true);
1586            mCameraDevice.cancelAutoFocus();
1587        }
1588        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1589            clearFocusState();
1590        }
1591    }
1592
1593    private void clearFocusState() {
1594        mFocusState = FOCUS_NOT_STARTED;
1595        updateFocusIndicator();
1596    }
1597
1598    private void updateFocusIndicator() {
1599        if (mFocusRectangle == null) return;
1600
1601        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1602            mFocusRectangle.showStart();
1603        } else if (mFocusState == FOCUS_SUCCESS) {
1604            mFocusRectangle.showSuccess();
1605        } else if (mFocusState == FOCUS_FAIL) {
1606            mFocusRectangle.showFail();
1607        } else {
1608            mFocusRectangle.clear();
1609        }
1610    }
1611
1612    @Override
1613    public void onBackPressed() {
1614        if (!isCameraIdle()) {
1615            // ignore backs while we're taking a picture
1616            return;
1617        } else if (!collapseCameraControls()) {
1618            super.onBackPressed();
1619        }
1620    }
1621
1622    @Override
1623    public boolean onKeyDown(int keyCode, KeyEvent event) {
1624        switch (keyCode) {
1625            case KeyEvent.KEYCODE_FOCUS:
1626                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1627                    doFocus(true);
1628                }
1629                return true;
1630            case KeyEvent.KEYCODE_CAMERA:
1631                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1632                    doSnap();
1633                }
1634                return true;
1635            case KeyEvent.KEYCODE_DPAD_CENTER:
1636                // If we get a dpad center event without any focused view, move
1637                // the focus to the shutter button and press it.
1638                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1639                    // Start auto-focus immediately to reduce shutter lag. After
1640                    // the shutter button gets the focus, doFocus() will be
1641                    // called again but it is fine.
1642                    if (collapseCameraControls()) return true;
1643                    doFocus(true);
1644                    if (mShutterButton.isInTouchMode()) {
1645                        mShutterButton.requestFocusFromTouch();
1646                    } else {
1647                        mShutterButton.requestFocus();
1648                    }
1649                    mShutterButton.setPressed(true);
1650                }
1651                return true;
1652        }
1653
1654        return super.onKeyDown(keyCode, event);
1655    }
1656
1657    @Override
1658    public boolean onKeyUp(int keyCode, KeyEvent event) {
1659        switch (keyCode) {
1660            case KeyEvent.KEYCODE_FOCUS:
1661                if (mFirstTimeInitialized) {
1662                    doFocus(false);
1663                }
1664                return true;
1665        }
1666        return super.onKeyUp(keyCode, event);
1667    }
1668
1669    private void doSnap() {
1670        if (collapseCameraControls()) return;
1671
1672        Log.v(TAG, "doSnap: mFocusState=" + mFocusState);
1673        // If the user has half-pressed the shutter and focus is completed, we
1674        // can take the photo right away. If the focus mode is infinity, we can
1675        // also take the photo.
1676        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1677                || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1678                || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)
1679                || (mFocusState == FOCUS_SUCCESS
1680                || mFocusState == FOCUS_FAIL)) {
1681            mImageCapture.onSnap();
1682        } else if (mFocusState == FOCUSING) {
1683            // Half pressing the shutter (i.e. the focus button event) will
1684            // already have requested AF for us, so just request capture on
1685            // focus here.
1686            mFocusState = FOCUSING_SNAP_ON_FINISH;
1687        } else if (mFocusState == FOCUS_NOT_STARTED) {
1688            // Focus key down event is dropped for some reasons. Just ignore.
1689        }
1690    }
1691
1692    private void doFocus(boolean pressed) {
1693        // Do the focus if the mode is not infinity.
1694        if (collapseCameraControls()) return;
1695        if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1696                  || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1697                  || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) {
1698            if (pressed) {  // Focus key down.
1699                autoFocus();
1700            } else {  // Focus key up.
1701                cancelAutoFocus();
1702            }
1703        }
1704    }
1705
1706    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1707        // Make sure we have a surface in the holder before proceeding.
1708        if (holder.getSurface() == null) {
1709            Log.d(TAG, "holder.getSurface() == null");
1710            return;
1711        }
1712
1713        // We need to save the holder for later use, even when the mCameraDevice
1714        // is null. This could happen if onResume() is invoked after this
1715        // function.
1716        mSurfaceHolder = holder;
1717
1718        // The mCameraDevice will be null if it fails to connect to the camera
1719        // hardware. In this case we will show a dialog and then finish the
1720        // activity, so it's OK to ignore it.
1721        if (mCameraDevice == null) return;
1722
1723        // Sometimes surfaceChanged is called after onPause or before onResume.
1724        // Ignore it.
1725        if (mPausing || isFinishing()) return;
1726
1727        if (mPreviewing && holder.isCreating()) {
1728            // Set preview display if the surface is being created and preview
1729            // was already started. That means preview display was set to null
1730            // and we need to set it now.
1731            setPreviewDisplay(holder);
1732        } else {
1733            // 1. Restart the preview if the size of surface was changed. The
1734            // framework may not support changing preview display on the fly.
1735            // 2. Start the preview now if surface was destroyed and preview
1736            // stopped.
1737            restartPreview();
1738        }
1739
1740        // If first time initialization is not finished, send a message to do
1741        // it later. We want to finish surfaceChanged as soon as possible to let
1742        // user see preview first.
1743        if (!mFirstTimeInitialized) {
1744            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1745        } else {
1746            initializeSecondTime();
1747        }
1748    }
1749
1750    public void surfaceCreated(SurfaceHolder holder) {
1751    }
1752
1753    public void surfaceDestroyed(SurfaceHolder holder) {
1754        stopPreview();
1755        mSurfaceHolder = null;
1756    }
1757
1758    private void closeCamera() {
1759        if (mCameraDevice != null) {
1760            CameraHolder.instance().release();
1761            mCameraDevice.setZoomChangeListener(null);
1762            mCameraDevice = null;
1763            mPreviewing = false;
1764        }
1765    }
1766
1767    private void ensureCameraDevice() throws CameraHardwareException {
1768        if (mCameraDevice == null) {
1769            mCameraDevice = CameraHolder.instance().open(mCameraId);
1770            mInitialParams = mCameraDevice.getParameters();
1771        }
1772    }
1773
1774    private void showCameraErrorAndFinish() {
1775        Resources ress = getResources();
1776        Util.showFatalErrorAndFinish(Camera.this,
1777                ress.getString(R.string.camera_error_title),
1778                ress.getString(R.string.cannot_connect_camera));
1779    }
1780
1781    private boolean restartPreview() {
1782        try {
1783            startPreview();
1784        } catch (CameraHardwareException e) {
1785            showCameraErrorAndFinish();
1786            return false;
1787        }
1788        return true;
1789    }
1790
1791    private void setPreviewDisplay(SurfaceHolder holder) {
1792        try {
1793            mCameraDevice.setPreviewDisplay(holder);
1794        } catch (Throwable ex) {
1795            closeCamera();
1796            throw new RuntimeException("setPreviewDisplay failed", ex);
1797        }
1798    }
1799
1800    private void startPreview() throws CameraHardwareException {
1801        if (mPausing || isFinishing()) return;
1802
1803        ensureCameraDevice();
1804        mCameraDevice.setErrorCallback(mErrorCallback);
1805
1806        // If we're previewing already, stop the preview first (this will blank
1807        // the screen).
1808        if (mPreviewing) stopPreview();
1809
1810        setPreviewDisplay(mSurfaceHolder);
1811        Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice);
1812        setCameraParameters(UPDATE_PARAM_ALL);
1813
1814
1815        try {
1816            Log.v(TAG, "startPreview");
1817            mCameraDevice.startPreview();
1818        } catch (Throwable ex) {
1819            closeCamera();
1820            throw new RuntimeException("startPreview failed", ex);
1821        }
1822        mPreviewing = true;
1823        mZoomState = ZOOM_STOPPED;
1824        mStatus = IDLE;
1825    }
1826
1827    private void stopPreview() {
1828        if (mCameraDevice != null && mPreviewing) {
1829            Log.v(TAG, "stopPreview");
1830            mCameraDevice.stopPreview();
1831        }
1832        mPreviewing = false;
1833        // If auto focus was in progress, it would have been canceled.
1834        clearFocusState();
1835    }
1836
1837    private static boolean isSupported(String value, List<String> supported) {
1838        return supported == null ? false : supported.indexOf(value) >= 0;
1839    }
1840
1841    private void updateCameraParametersInitialize() {
1842        // Reset preview frame rate to the maximum because it may be lowered by
1843        // video camera application.
1844        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1845        if (frameRates != null) {
1846            Integer max = Collections.max(frameRates);
1847            mParameters.setPreviewFrameRate(max);
1848        }
1849
1850    }
1851
1852    private void updateCameraParametersZoom() {
1853        // Set zoom.
1854        if (mParameters.isZoomSupported()) {
1855            mParameters.setZoom(mZoomValue);
1856        }
1857    }
1858
1859    private void updateCameraParametersPreference() {
1860        // Set picture size.
1861        String pictureSize = mPreferences.getString(
1862                CameraSettings.KEY_PICTURE_SIZE, null);
1863        if (pictureSize == null) {
1864            CameraSettings.initialCameraPictureSize(this, mParameters);
1865        } else {
1866            List<Size> supported = mParameters.getSupportedPictureSizes();
1867            CameraSettings.setCameraPictureSize(
1868                    pictureSize, supported, mParameters);
1869        }
1870
1871        // Set the preview frame aspect ratio according to the picture size.
1872        Size size = mParameters.getPictureSize();
1873        PreviewFrameLayout frameLayout =
1874                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1875        frameLayout.setAspectRatio((double) size.width / size.height);
1876
1877        // Set a preview size that is closest to the viewfinder height and has
1878        // the right aspect ratio.
1879        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1880        Size optimalSize = Util.getOptimalPreviewSize(this,
1881                sizes, (double) size.width / size.height);
1882        if (optimalSize != null) {
1883            Size original = mParameters.getPreviewSize();
1884            if (!original.equals(optimalSize)) {
1885                mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1886
1887                // Zoom related settings will be changed for different preview
1888                // sizes, so set and read the parameters to get lastest values
1889                mCameraDevice.setParameters(mParameters);
1890                mParameters = mCameraDevice.getParameters();
1891            }
1892        }
1893
1894        // Since change scene mode may change supported values,
1895        // Set scene mode first,
1896        mSceneMode = mPreferences.getString(
1897                CameraSettings.KEY_SCENE_MODE,
1898                getString(R.string.pref_camera_scenemode_default));
1899        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1900            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1901                mParameters.setSceneMode(mSceneMode);
1902                mCameraDevice.setParameters(mParameters);
1903
1904                // Setting scene mode will change the settings of flash mode,
1905                // white balance, and focus mode. Here we read back the
1906                // parameters, so we can know those settings.
1907                mParameters = mCameraDevice.getParameters();
1908            }
1909        } else {
1910            mSceneMode = mParameters.getSceneMode();
1911            if (mSceneMode == null) {
1912                mSceneMode = Parameters.SCENE_MODE_AUTO;
1913            }
1914        }
1915
1916        // Set JPEG quality.
1917        String jpegQuality = mPreferences.getString(
1918                CameraSettings.KEY_JPEG_QUALITY,
1919                getString(R.string.pref_camera_jpegquality_default));
1920        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
1921
1922        // For the following settings, we need to check if the settings are
1923        // still supported by latest driver, if not, ignore the settings.
1924
1925        // Set color effect parameter.
1926        String colorEffect = mPreferences.getString(
1927                CameraSettings.KEY_COLOR_EFFECT,
1928                getString(R.string.pref_camera_coloreffect_default));
1929        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1930            mParameters.setColorEffect(colorEffect);
1931        }
1932
1933        // Set exposure compensation
1934        String exposure = mPreferences.getString(
1935                CameraSettings.KEY_EXPOSURE,
1936                getString(R.string.pref_exposure_default));
1937        try {
1938            int value = Integer.parseInt(exposure);
1939            int max = mParameters.getMaxExposureCompensation();
1940            int min = mParameters.getMinExposureCompensation();
1941            if (value >= min && value <= max) {
1942                mParameters.setExposureCompensation(value);
1943            } else {
1944                Log.w(TAG, "invalid exposure range: " + exposure);
1945            }
1946        } catch (NumberFormatException e) {
1947            Log.w(TAG, "invalid exposure: " + exposure);
1948        }
1949
1950        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1951            // Set flash mode.
1952            String flashMode = mPreferences.getString(
1953                    CameraSettings.KEY_FLASH_MODE,
1954                    getString(R.string.pref_camera_flashmode_default));
1955            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1956            if (isSupported(flashMode, supportedFlash)) {
1957                mParameters.setFlashMode(flashMode);
1958            } else {
1959                flashMode = mParameters.getFlashMode();
1960                if (flashMode == null) {
1961                    flashMode = getString(
1962                            R.string.pref_camera_flashmode_no_flash);
1963                }
1964            }
1965
1966            // Set white balance parameter.
1967            String whiteBalance = mPreferences.getString(
1968                    CameraSettings.KEY_WHITE_BALANCE,
1969                    getString(R.string.pref_camera_whitebalance_default));
1970            if (isSupported(whiteBalance,
1971                    mParameters.getSupportedWhiteBalance())) {
1972                mParameters.setWhiteBalance(whiteBalance);
1973            } else {
1974                whiteBalance = mParameters.getWhiteBalance();
1975                if (whiteBalance == null) {
1976                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1977                }
1978            }
1979
1980            // Set focus mode.
1981            mFocusMode = mPreferences.getString(
1982                    CameraSettings.KEY_FOCUS_MODE,
1983                    getString(R.string.pref_camera_focusmode_default));
1984            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1985                mParameters.setFocusMode(mFocusMode);
1986            } else {
1987                mFocusMode = mParameters.getFocusMode();
1988                if (mFocusMode == null) {
1989                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
1990                }
1991            }
1992        } else {
1993            mFocusMode = mParameters.getFocusMode();
1994        }
1995    }
1996
1997    // We separate the parameters into several subsets, so we can update only
1998    // the subsets actually need updating. The PREFERENCE set needs extra
1999    // locking because the preference can be changed from GLThread as well.
2000    private void setCameraParameters(int updateSet) {
2001        mParameters = mCameraDevice.getParameters();
2002
2003        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
2004            updateCameraParametersInitialize();
2005        }
2006
2007        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
2008            updateCameraParametersZoom();
2009        }
2010
2011        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
2012            updateCameraParametersPreference();
2013        }
2014
2015        mCameraDevice.setParameters(mParameters);
2016    }
2017
2018    // If the Camera is idle, update the parameters immediately, otherwise
2019    // accumulate them in mUpdateSet and update later.
2020    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
2021        mUpdateSet |= additionalUpdateSet;
2022        if (mCameraDevice == null) {
2023            // We will update all the parameters when we open the device, so
2024            // we don't need to do anything now.
2025            mUpdateSet = 0;
2026            return;
2027        } else if (isCameraIdle()) {
2028            setCameraParameters(mUpdateSet);
2029            updateSceneModeUI();
2030            mUpdateSet = 0;
2031        } else {
2032            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
2033                mHandler.sendEmptyMessageDelayed(
2034                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
2035            }
2036        }
2037    }
2038
2039    private void gotoGallery() {
2040        MenuHelper.gotoCameraImageGallery(this);
2041    }
2042
2043    private void viewImage(RotateImageView view) {
2044        if(!view.isUriValid()) {
2045            Log.e(TAG, "Uri invalid. uri=" + view.getUri());
2046            return;
2047        }
2048
2049        try {
2050            startActivity(new Intent(
2051                    Util.REVIEW_ACTION, view.getUri()));
2052        } catch (ActivityNotFoundException ex) {
2053            try {
2054                startActivity(new Intent(
2055                        Intent.ACTION_VIEW, view.getUri()));
2056            } catch (ActivityNotFoundException e) {
2057                Log.e(TAG, "review image fail. uri=" + view.getUri(), e);
2058            }
2059        }
2060    }
2061
2062    private void startReceivingLocationUpdates() {
2063        if (mLocationManager != null) {
2064            try {
2065                mLocationManager.requestLocationUpdates(
2066                        LocationManager.NETWORK_PROVIDER,
2067                        1000,
2068                        0F,
2069                        mLocationListeners[1]);
2070            } catch (java.lang.SecurityException ex) {
2071                Log.i(TAG, "fail to request location update, ignore", ex);
2072            } catch (IllegalArgumentException ex) {
2073                Log.d(TAG, "provider does not exist " + ex.getMessage());
2074            }
2075            try {
2076                mLocationManager.requestLocationUpdates(
2077                        LocationManager.GPS_PROVIDER,
2078                        1000,
2079                        0F,
2080                        mLocationListeners[0]);
2081                showGpsOnScreenIndicator(false);
2082            } catch (java.lang.SecurityException ex) {
2083                Log.i(TAG, "fail to request location update, ignore", ex);
2084            } catch (IllegalArgumentException ex) {
2085                Log.d(TAG, "provider does not exist " + ex.getMessage());
2086            }
2087        }
2088    }
2089
2090    private void stopReceivingLocationUpdates() {
2091        if (mLocationManager != null) {
2092            for (int i = 0; i < mLocationListeners.length; i++) {
2093                try {
2094                    mLocationManager.removeUpdates(mLocationListeners[i]);
2095                } catch (Exception ex) {
2096                    Log.i(TAG, "fail to remove location listners, ignore", ex);
2097                }
2098            }
2099        }
2100        hideGpsOnScreenIndicator();
2101    }
2102
2103    private Location getCurrentLocation() {
2104        // go in best to worst order
2105        for (int i = 0; i < mLocationListeners.length; i++) {
2106            Location l = mLocationListeners[i].current();
2107            if (l != null) return l;
2108        }
2109        return null;
2110    }
2111
2112    private boolean isCameraIdle() {
2113        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
2114    }
2115
2116    private boolean isImageCaptureIntent() {
2117        String action = getIntent().getAction();
2118        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
2119    }
2120
2121    private void setupCaptureParams() {
2122        Bundle myExtras = getIntent().getExtras();
2123        if (myExtras != null) {
2124            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2125            mCropValue = myExtras.getString("crop");
2126        }
2127    }
2128
2129    private void showPostCaptureAlert() {
2130        if (mIsImageCaptureIntent) {
2131            if (mIndicatorWheel == null) {
2132                mShutterButton.setVisibility(View.INVISIBLE);
2133            }
2134            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2135            for (int id : pickIds) {
2136                View button = findViewById(id);
2137                ((View) button.getParent()).setVisibility(View.VISIBLE);
2138            }
2139        }
2140    }
2141
2142    private void hidePostCaptureAlert() {
2143        if (mIsImageCaptureIntent) {
2144            if (mIndicatorWheel == null) {
2145                mShutterButton.setVisibility(View.VISIBLE);
2146            }
2147            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2148            for (int id : pickIds) {
2149                View button = findViewById(id);
2150                ((View) button.getParent()).setVisibility(View.GONE);
2151            }
2152        }
2153    }
2154
2155    private int calculatePicturesRemaining() {
2156        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
2157        return mPicturesRemaining;
2158    }
2159
2160    @Override
2161    public boolean onPrepareOptionsMenu(Menu menu) {
2162        super.onPrepareOptionsMenu(menu);
2163        // Only show the menu when camera is idle.
2164        for (int i = 0; i < menu.size(); i++) {
2165            menu.getItem(i).setVisible(isCameraIdle());
2166        }
2167
2168        return true;
2169    }
2170
2171    @Override
2172    public boolean onCreateOptionsMenu(Menu menu) {
2173        super.onCreateOptionsMenu(menu);
2174
2175        if (mIsImageCaptureIntent) {
2176            // No options menu for attach mode.
2177            return false;
2178        } else {
2179            addBaseMenuItems(menu);
2180        }
2181        return true;
2182    }
2183
2184    private void addBaseMenuItems(Menu menu) {
2185        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2186            public void run() {
2187                switchToVideoMode();
2188            }
2189        });
2190        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2191                MenuHelper.POSITION_GOTO_GALLERY,
2192                R.string.camera_gallery_photos_text)
2193                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2194            public boolean onMenuItemClick(MenuItem item) {
2195                gotoGallery();
2196                return true;
2197            }
2198        });
2199        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2200        mGalleryItems.add(gallery);
2201
2202        if (mNumberOfCameras > 1) {
2203            menu.add(Menu.NONE, Menu.NONE,
2204                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2205                    R.string.switch_camera_id)
2206                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2207                public boolean onMenuItemClick(MenuItem item) {
2208                    CameraSettings.writePreferredCameraId(mPreferences,
2209                            ((mCameraId == mFrontCameraId)
2210                            ? mBackCameraId : mFrontCameraId));
2211                    onSharedPreferenceChanged();
2212                    return true;
2213                }
2214            }).setIcon(android.R.drawable.ic_menu_camera);
2215        }
2216    }
2217
2218    private void switchCameraId(int cameraId) {
2219        if (mPausing || !isCameraIdle()) return;
2220        mCameraId = cameraId;
2221
2222        stopPreview();
2223        closeCamera();
2224
2225        // Remove the messages in the event queue.
2226        mHandler.removeMessages(RESTART_PREVIEW);
2227
2228        // Reset variables
2229        mJpegPictureCallbackTime = 0;
2230        mZoomValue = 0;
2231
2232        // Reload the preferences.
2233        mPreferences.setLocalId(this, mCameraId);
2234        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2235
2236        // Restart the preview.
2237        resetExposureCompensation();
2238        if (!restartPreview()) return;
2239
2240        initializeZoom();
2241
2242        // Reload the UI.
2243        initializeHeadUpDisplay();
2244        initializeControlPanel();
2245    }
2246
2247    private boolean switchToVideoMode() {
2248        if (isFinishing() || !isCameraIdle()) return false;
2249        MenuHelper.gotoVideoMode(Camera.this);
2250        mHandler.removeMessages(FIRST_TIME_INIT);
2251        finish();
2252        return true;
2253    }
2254
2255    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2256        if (onOff == SWITCH_VIDEO) {
2257            return switchToVideoMode();
2258        } else {
2259            return true;
2260        }
2261    }
2262
2263    private void onSharedPreferenceChanged() {
2264        // ignore the events after "onPause()"
2265        if (mPausing) return;
2266
2267        boolean recordLocation;
2268
2269        recordLocation = RecordLocationPreference.get(
2270                mPreferences, getContentResolver());
2271
2272        if (mRecordLocation != recordLocation) {
2273            mRecordLocation = recordLocation;
2274            if (mRecordLocation) {
2275                startReceivingLocationUpdates();
2276            } else {
2277                stopReceivingLocationUpdates();
2278            }
2279        }
2280        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
2281        if (mCameraId != cameraId) {
2282            switchCameraId(cameraId);
2283        } else {
2284            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2285        }
2286    }
2287
2288    @Override
2289    public void onUserInteraction() {
2290        super.onUserInteraction();
2291        keepScreenOnAwhile();
2292    }
2293
2294    private void resetScreenOn() {
2295        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2296        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2297    }
2298
2299    private void keepScreenOnAwhile() {
2300        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2301        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2302        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2303    }
2304
2305    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2306
2307        public void onSharedPreferenceChanged() {
2308            Camera.this.onSharedPreferenceChanged();
2309        }
2310
2311        public void onRestorePreferencesClicked() {
2312            Camera.this.onRestorePreferencesClicked();
2313        }
2314
2315        public void onPopupWindowVisibilityChanged(int visibility) {
2316        }
2317    }
2318
2319    protected void onRestorePreferencesClicked() {
2320        if (mPausing) return;
2321        Runnable runnable = new Runnable() {
2322            public void run() {
2323                if (mHeadUpDisplay != null) {
2324                    mHeadUpDisplay.restorePreferences(mParameters);
2325                }
2326            }
2327        };
2328        MenuHelper.confirmAction(this,
2329                getString(R.string.confirm_restore_title),
2330                getString(R.string.confirm_restore_message),
2331                runnable);
2332    }
2333
2334    private class MyControlPanelListener implements ControlPanel.Listener {
2335        public void onSharedPreferenceChanged() {
2336            Camera.this.onSharedPreferenceChanged();
2337        }
2338    }
2339
2340    private class MyCameraPickerListener implements CameraPicker.Listener {
2341        public void onSharedPreferenceChanged() {
2342            Camera.this.onSharedPreferenceChanged();
2343        }
2344    }
2345}
2346