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