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