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