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