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