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