Camera.java revision 0042b3b48b693a46030ec02f31df625b767e4977
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 // 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 } 704 705 if (!mIsImageCaptureIntent) { 706 Size s = mParameters.getPictureSize(); 707 mImageSaver.addImage(jpegData, mLocation, s.width, s.height); 708 } else { 709 mJpegImageData = jpegData; 710 if (!mQuickCapture) { 711 showPostCaptureAlert(); 712 } else { 713 doAttach(); 714 } 715 } 716 717 // Check this in advance of each shot so we don't add to shutter 718 // latency. It's true that someone else could write to the SD card in 719 // the mean time and fill it, but that could have happened between the 720 // shutter press and saving the JPEG too. 721 checkStorage(); 722 723 long now = System.currentTimeMillis(); 724 mJpegCallbackFinishTime = now - mJpegPictureCallbackTime; 725 Log.v(TAG, "mJpegCallbackFinishTime = " 726 + mJpegCallbackFinishTime + "ms"); 727 mJpegPictureCallbackTime = 0; 728 } 729 } 730 731 private final class AutoFocusCallback 732 implements android.hardware.Camera.AutoFocusCallback { 733 public void onAutoFocus( 734 boolean focused, android.hardware.Camera camera) { 735 if (mPausing) return; 736 737 mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime; 738 Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms"); 739 mFocusManager.onAutoFocus(focused); 740 // If focus completes and the snapshot is not started, enable the 741 // controls. 742 if (mFocusManager.isFocusCompleted()) { 743 enableCameraControls(true); 744 } 745 } 746 } 747 748 private final class ZoomListener 749 implements android.hardware.Camera.OnZoomChangeListener { 750 @Override 751 public void onZoomChange( 752 int value, boolean stopped, android.hardware.Camera camera) { 753 Log.v(TAG, "Zoom changed: value=" + value + ". stopped=" + stopped); 754 mZoomValue = value; 755 756 // Update the UI when we get zoom value. 757 mZoomControl.setZoomIndex(value); 758 759 // Keep mParameters up to date. We do not getParameter again in 760 // takePicture. If we do not do this, wrong zoom value will be set. 761 mParameters.setZoom(value); 762 763 if (stopped && mZoomState != ZOOM_STOPPED) { 764 if (mTargetZoomValue != -1 && value != mTargetZoomValue) { 765 mCameraDevice.startSmoothZoom(mTargetZoomValue); 766 mZoomState = ZOOM_START; 767 } else { 768 mZoomState = ZOOM_STOPPED; 769 } 770 } 771 } 772 } 773 774 // Each SaveRequest remembers the data needed to save an image. 775 private static class SaveRequest { 776 byte[] data; 777 Location loc; 778 int width, height; 779 long dateTaken; 780 int previewWidth; 781 } 782 783 // We use a queue to store the SaveRequests that have not been completed 784 // yet. The main thread puts the request into the queue. The saver thread 785 // gets it from the queue, does the work, and removes it from the queue. 786 // 787 // There are several cases the main thread needs to wait for the saver 788 // thread to finish all the work in the queue: 789 // (1) When the activity's onPause() is called, we need to finish all the 790 // work, so other programs (like Gallery) can see all the images. 791 // (2) When we need to show the SharePop, we need to finish all the work 792 // too, because we want to show the thumbnail of the last image taken. 793 // 794 // If the queue becomes too long, adding a new request will block the main 795 // thread until the queue length drops below the threshold (QUEUE_LIMIT). 796 // If we don't do this, we may face several problems: (1) We may OOM 797 // because we are holding all the jpeg data in memory. (2) We may ANR 798 // when we need to wait for saver thread finishing all the work (in 799 // onPause() or showSharePopup()) because the time to finishing a long queue 800 // of work may be too long. 801 private class ImageSaver extends Thread { 802 private static final int QUEUE_LIMIT = 3; 803 804 private ArrayList<SaveRequest> mQueue; 805 private Thumbnail mPendingThumbnail; 806 private Object mUpdateThumbnailLock = new Object(); 807 private boolean mStop; 808 809 // Runs in main thread 810 public ImageSaver() { 811 mQueue = new ArrayList<SaveRequest>(); 812 start(); 813 } 814 815 // Runs in main thread 816 public void addImage(final byte[] data, Location loc, int width, 817 int height) { 818 SaveRequest r = new SaveRequest(); 819 r.data = data; 820 r.loc = (loc == null) ? null : new Location(loc); // make a copy 821 r.width = width; 822 r.height = height; 823 r.dateTaken = System.currentTimeMillis(); 824 r.previewWidth = mPreviewFrameLayout.getWidth(); 825 synchronized (this) { 826 while (mQueue.size() >= QUEUE_LIMIT) { 827 try { 828 wait(); 829 } catch (InterruptedException ex) { 830 // ignore. 831 } 832 } 833 mQueue.add(r); 834 notifyAll(); // Tell saver thread there is new work to do. 835 } 836 } 837 838 // Runs in saver thread 839 @Override 840 public void run() { 841 while (true) { 842 SaveRequest r; 843 synchronized (this) { 844 if (mQueue.isEmpty()) { 845 notifyAll(); // notify main thread in waitDone 846 847 // Note that we can only stop after we saved all images 848 // in the queue. 849 if (mStop) break; 850 851 try { 852 wait(); 853 } catch (InterruptedException ex) { 854 // ignore. 855 } 856 continue; 857 } 858 r = mQueue.get(0); 859 } 860 storeImage(r.data, r.loc, r.width, r.height, r.dateTaken, 861 r.previewWidth); 862 synchronized(this) { 863 mQueue.remove(0); 864 notifyAll(); // the main thread may wait in addImage 865 } 866 } 867 } 868 869 // Runs in main thread 870 public void waitDone() { 871 synchronized (this) { 872 while (!mQueue.isEmpty()) { 873 try { 874 wait(); 875 } catch (InterruptedException ex) { 876 // ignore. 877 } 878 } 879 } 880 updateThumbnail(); 881 } 882 883 // Runs in main thread 884 public void finish() { 885 waitDone(); 886 synchronized (this) { 887 mStop = true; 888 notifyAll(); 889 } 890 try { 891 join(); 892 } catch (InterruptedException ex) { 893 // ignore. 894 } 895 } 896 897 // Runs in main thread (because we need to update mThumbnailView in the 898 // main thread) 899 public void updateThumbnail() { 900 Thumbnail t; 901 synchronized (mUpdateThumbnailLock) { 902 mHandler.removeMessages(UPDATE_THUMBNAIL); 903 t = mPendingThumbnail; 904 mPendingThumbnail = null; 905 } 906 907 if (t != null) { 908 mThumbnail = t; 909 mThumbnailView.setBitmap(mThumbnail.getBitmap()); 910 } 911 // Share popup may still have the reference to the old thumbnail. Clear it. 912 mSharePopup = null; 913 } 914 915 // Runs in saver thread 916 private void storeImage(final byte[] data, Location loc, int width, 917 int height, long dateTaken, int previewWidth) { 918 String title = Util.createJpegName(dateTaken); 919 int orientation = Exif.getOrientation(data); 920 Uri uri = Storage.addImage(mContentResolver, title, dateTaken, 921 loc, orientation, data, width, height); 922 if (uri != null) { 923 boolean needThumbnail; 924 synchronized (this) { 925 // If the number of requests in the queue (include the 926 // current one) is greater than 1, we don't need to generate 927 // thumbnail for this image. Because we'll soon replace it 928 // with the thumbnail for some image later in the queue. 929 needThumbnail = (mQueue.size() <= 1); 930 } 931 if (needThumbnail) { 932 // Create a thumbnail whose width is equal or bigger than 933 // that of the preview. 934 int ratio = (int) Math.ceil((double) width / previewWidth); 935 int inSampleSize = Integer.highestOneBit(ratio); 936 Thumbnail t = Thumbnail.createThumbnail( 937 data, orientation, inSampleSize, uri); 938 synchronized (mUpdateThumbnailLock) { 939 // We need to update the thumbnail in the main thread, 940 // so send a message to run updateThumbnail(). 941 mPendingThumbnail = t; 942 mHandler.sendEmptyMessage(UPDATE_THUMBNAIL); 943 } 944 } 945 Util.broadcastNewPicture(Camera.this, uri); 946 } 947 } 948 } 949 950 @Override 951 public boolean capture() { 952 // If we are already in the middle of taking a snapshot then ignore. 953 if (mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) { 954 return false; 955 } 956 mCaptureStartTime = System.currentTimeMillis(); 957 mPostViewPictureCallbackTime = 0; 958 enableCameraControls(false); 959 mJpegImageData = null; 960 961 // Set rotation and gps data. 962 Util.setRotationParameter(mParameters, mCameraId, mOrientation); 963 Location loc = mLocationManager.getCurrentLocation(); 964 Util.setGpsParameters(mParameters, loc); 965 mCameraDevice.setParameters(mParameters); 966 967 mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, 968 mPostViewPictureCallback, new JpegPictureCallback(loc)); 969 mCameraState = SNAPSHOT_IN_PROGRESS; 970 return true; 971 } 972 973 @Override 974 public void setFocusParameters() { 975 setCameraParameters(UPDATE_PARAM_PREFERENCE); 976 } 977 978 private boolean saveDataToFile(String filePath, byte[] data) { 979 FileOutputStream f = null; 980 try { 981 f = new FileOutputStream(filePath); 982 f.write(data); 983 } catch (IOException e) { 984 return false; 985 } finally { 986 Util.closeSilently(f); 987 } 988 return true; 989 } 990 991 private void getPreferredCameraId() { 992 mPreferences = new ComboPreferences(this); 993 CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal()); 994 mCameraId = CameraSettings.readPreferredCameraId(mPreferences); 995 996 // Testing purpose. Launch a specific camera through the intent extras. 997 int intentCameraId = Util.getCameraFacingIntentExtras(this); 998 if (intentCameraId != -1) { 999 mCameraId = intentCameraId; 1000 } 1001 } 1002 1003 Thread mCameraOpenThread = new Thread(new Runnable() { 1004 public void run() { 1005 try { 1006 mCameraDevice = Util.openCamera(Camera.this, mCameraId); 1007 } catch (CameraHardwareException e) { 1008 mOpenCameraFail = true; 1009 } catch (CameraDisabledException e) { 1010 mCameraDisabled = true; 1011 } 1012 } 1013 }); 1014 1015 Thread mCameraPreviewThread = new Thread(new Runnable() { 1016 public void run() { 1017 initializeCapabilities(); 1018 startPreview(); 1019 } 1020 }); 1021 1022 @Override 1023 public void onCreate(Bundle icicle) { 1024 super.onCreate(icicle); 1025 getPreferredCameraId(); 1026 mFocusManager = new FocusManager(mPreferences, 1027 getString(R.string.pref_camera_focusmode_default)); 1028 1029 /* 1030 * To reduce startup time, we start the camera open and preview threads. 1031 * We make sure the preview is started at the end of onCreate. 1032 */ 1033 mCameraOpenThread.start(); 1034 1035 mIsImageCaptureIntent = isImageCaptureIntent(); 1036 setContentView(R.layout.camera); 1037 if (mIsImageCaptureIntent) { 1038 mReviewDoneButton = (Rotatable) findViewById(R.id.btn_done); 1039 mReviewCancelButton = (Rotatable) findViewById(R.id.btn_cancel); 1040 findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE); 1041 } else { 1042 mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail); 1043 mThumbnailView.enableFilter(false); 1044 mThumbnailView.setVisibility(View.VISIBLE); 1045 } 1046 1047 mPreferences.setLocalId(this, mCameraId); 1048 CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); 1049 1050 mNumberOfCameras = CameraHolder.instance().getNumberOfCameras(); 1051 mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); 1052 1053 // we need to reset exposure for the preview 1054 resetExposureCompensation(); 1055 1056 Util.enterLightsOutMode(getWindow()); 1057 1058 // don't set mSurfaceHolder here. We have it set ONLY within 1059 // surfaceChanged / surfaceDestroyed, other parts of the code 1060 // assume that when it is set, the surface is also set. 1061 SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview); 1062 SurfaceHolder holder = preview.getHolder(); 1063 holder.addCallback(this); 1064 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 1065 1066 // Make sure camera device is opened. 1067 try { 1068 mCameraOpenThread.join(); 1069 mCameraOpenThread = null; 1070 if (mOpenCameraFail) { 1071 Util.showErrorAndFinish(this, R.string.cannot_connect_camera); 1072 return; 1073 } else if (mCameraDisabled) { 1074 Util.showErrorAndFinish(this, R.string.camera_disabled); 1075 return; 1076 } 1077 } catch (InterruptedException ex) { 1078 // ignore 1079 } 1080 mCameraPreviewThread.start(); 1081 1082 if (mIsImageCaptureIntent) { 1083 setupCaptureParams(); 1084 } else { 1085 mModePicker = (ModePicker) findViewById(R.id.mode_picker); 1086 mModePicker.setVisibility(View.VISIBLE); 1087 mModePicker.setOnModeChangeListener(this); 1088 mModePicker.setCurrentMode(ModePicker.MODE_CAMERA); 1089 } 1090 1091 mZoomControl = (ZoomControl) findViewById(R.id.zoom_control); 1092 mLocationManager = new LocationManager(this, this); 1093 1094 mBackCameraId = CameraHolder.instance().getBackCameraId(); 1095 mFrontCameraId = CameraHolder.instance().getFrontCameraId(); 1096 1097 // Wait until the camera settings are retrieved. 1098 synchronized (mCameraPreviewThread) { 1099 try { 1100 mCameraPreviewThread.wait(); 1101 } catch (InterruptedException ex) { 1102 // ignore 1103 } 1104 } 1105 1106 // Do this after starting preview because it depends on camera 1107 // parameters. 1108 initializeIndicatorControl(); 1109 1110 // Make sure preview is started. 1111 try { 1112 mCameraPreviewThread.join(); 1113 } catch (InterruptedException ex) { 1114 // ignore 1115 } 1116 mCameraPreviewThread = null; 1117 } 1118 1119 private void overrideCameraSettings(final String flashMode, 1120 final String whiteBalance, final String focusMode) { 1121 if (mIndicatorControlContainer != null) { 1122 mIndicatorControlContainer.overrideSettings( 1123 CameraSettings.KEY_FLASH_MODE, flashMode, 1124 CameraSettings.KEY_WHITE_BALANCE, whiteBalance, 1125 CameraSettings.KEY_FOCUS_MODE, focusMode); 1126 } 1127 } 1128 1129 private void updateSceneModeUI() { 1130 // If scene mode is set, we cannot set flash mode, white balance, and 1131 // focus mode, instead, we read it from driver 1132 if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 1133 overrideCameraSettings(mParameters.getFlashMode(), 1134 mParameters.getWhiteBalance(), mParameters.getFocusMode()); 1135 } else { 1136 overrideCameraSettings(null, null, null); 1137 } 1138 } 1139 1140 private void loadCameraPreferences() { 1141 CameraSettings settings = new CameraSettings(this, mInitialParams, 1142 mCameraId, CameraHolder.instance().getCameraInfo()); 1143 mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences); 1144 } 1145 1146 private void initializeIndicatorControl() { 1147 // setting the indicator buttons. 1148 mIndicatorControlContainer = 1149 (IndicatorControlContainer) findViewById(R.id.indicator_control); 1150 if (mIndicatorControlContainer == null) return; 1151 loadCameraPreferences(); 1152 final String[] SETTING_KEYS = { 1153 CameraSettings.KEY_FLASH_MODE, 1154 CameraSettings.KEY_WHITE_BALANCE, 1155 CameraSettings.KEY_EXPOSURE, 1156 CameraSettings.KEY_SCENE_MODE}; 1157 final String[] OTHER_SETTING_KEYS = { 1158 CameraSettings.KEY_RECORD_LOCATION, 1159 CameraSettings.KEY_PICTURE_SIZE, 1160 CameraSettings.KEY_FOCUS_MODE}; 1161 1162 CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light); 1163 mIndicatorControlContainer.initialize(this, mPreferenceGroup, 1164 mParameters.isZoomSupported(), 1165 SETTING_KEYS, OTHER_SETTING_KEYS); 1166 updateSceneModeUI(); 1167 mIndicatorControlContainer.setListener(this); 1168 } 1169 1170 private boolean collapseCameraControls() { 1171 if ((mIndicatorControlContainer != null) 1172 && mIndicatorControlContainer.dismissSettingPopup()) { 1173 return true; 1174 } 1175 return false; 1176 } 1177 1178 private void enableCameraControls(boolean enable) { 1179 if (mIndicatorControlContainer != null) { 1180 mIndicatorControlContainer.setEnabled(enable); 1181 } 1182 if (mModePicker != null) mModePicker.setEnabled(enable); 1183 if (mZoomControl != null) mZoomControl.setEnabled(enable); 1184 if (mThumbnailView != null) mThumbnailView.setEnabled(enable); 1185 } 1186 1187 private class MyOrientationEventListener 1188 extends OrientationEventListener { 1189 public MyOrientationEventListener(Context context) { 1190 super(context); 1191 } 1192 1193 @Override 1194 public void onOrientationChanged(int orientation) { 1195 // We keep the last known orientation. So if the user first orient 1196 // the camera then point the camera to floor or sky, we still have 1197 // the correct orientation. 1198 if (orientation == ORIENTATION_UNKNOWN) return; 1199 mOrientation = Util.roundOrientation(orientation, mOrientation); 1200 // When the screen is unlocked, display rotation may change. Always 1201 // calculate the up-to-date orientationCompensation. 1202 int orientationCompensation = mOrientation 1203 + Util.getDisplayRotation(Camera.this); 1204 if (mOrientationCompensation != orientationCompensation) { 1205 mOrientationCompensation = orientationCompensation; 1206 setOrientationIndicator(mOrientationCompensation); 1207 } 1208 1209 // Show the toast after getting the first orientation changed. 1210 if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) { 1211 mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST); 1212 showTapToFocusToast(); 1213 } 1214 } 1215 } 1216 1217 private void setOrientationIndicator(int orientation) { 1218 Rotatable[] indicators = {mThumbnailView, mModePicker, mSharePopup, 1219 mIndicatorControlContainer, mZoomControl, mFocusIndicator, mFaceView, 1220 mReviewCancelButton, mReviewDoneButton}; 1221 for (Rotatable indicator : indicators) { 1222 if (indicator != null) indicator.setOrientation(orientation); 1223 } 1224 } 1225 1226 @Override 1227 public void onStop() { 1228 super.onStop(); 1229 if (mMediaProviderClient != null) { 1230 mMediaProviderClient.release(); 1231 mMediaProviderClient = null; 1232 } 1233 } 1234 1235 private void checkStorage() { 1236 mPicturesRemaining = Storage.getAvailableSpace(); 1237 if (mPicturesRemaining > Storage.LOW_STORAGE_THRESHOLD) { 1238 mPicturesRemaining = (mPicturesRemaining - Storage.LOW_STORAGE_THRESHOLD) 1239 / Storage.PICTURE_SIZE; 1240 } else if (mPicturesRemaining > 0) { 1241 mPicturesRemaining = 0; 1242 } 1243 1244 updateStorageHint(); 1245 } 1246 1247 @OnClickAttr 1248 public void onThumbnailClicked(View v) { 1249 if (isCameraIdle() && mThumbnail != null) { 1250 showSharePopup(); 1251 } 1252 } 1253 1254 @OnClickAttr 1255 public void onReviewRetakeClicked(View v) { 1256 hidePostCaptureAlert(); 1257 startPreview(); 1258 } 1259 1260 @OnClickAttr 1261 public void onReviewDoneClicked(View v) { 1262 doAttach(); 1263 } 1264 1265 @OnClickAttr 1266 public void onReviewCancelClicked(View v) { 1267 doCancel(); 1268 } 1269 1270 private void doAttach() { 1271 if (mPausing) { 1272 return; 1273 } 1274 1275 byte[] data = mJpegImageData; 1276 1277 if (mCropValue == null) { 1278 // First handle the no crop case -- just return the value. If the 1279 // caller specifies a "save uri" then write the data to it's 1280 // stream. Otherwise, pass back a scaled down version of the bitmap 1281 // directly in the extras. 1282 if (mSaveUri != null) { 1283 OutputStream outputStream = null; 1284 try { 1285 outputStream = mContentResolver.openOutputStream(mSaveUri); 1286 outputStream.write(data); 1287 outputStream.close(); 1288 1289 setResultEx(RESULT_OK); 1290 finish(); 1291 } catch (IOException ex) { 1292 // ignore exception 1293 } finally { 1294 Util.closeSilently(outputStream); 1295 } 1296 } else { 1297 int orientation = Exif.getOrientation(data); 1298 Bitmap bitmap = Util.makeBitmap(data, 50 * 1024); 1299 bitmap = Util.rotate(bitmap, orientation); 1300 setResultEx(RESULT_OK, 1301 new Intent("inline-data").putExtra("data", bitmap)); 1302 finish(); 1303 } 1304 } else { 1305 // Save the image to a temp file and invoke the cropper 1306 Uri tempUri = null; 1307 FileOutputStream tempStream = null; 1308 try { 1309 File path = getFileStreamPath(sTempCropFilename); 1310 path.delete(); 1311 tempStream = openFileOutput(sTempCropFilename, 0); 1312 tempStream.write(data); 1313 tempStream.close(); 1314 tempUri = Uri.fromFile(path); 1315 } catch (FileNotFoundException ex) { 1316 setResultEx(Activity.RESULT_CANCELED); 1317 finish(); 1318 return; 1319 } catch (IOException ex) { 1320 setResultEx(Activity.RESULT_CANCELED); 1321 finish(); 1322 return; 1323 } finally { 1324 Util.closeSilently(tempStream); 1325 } 1326 1327 Bundle newExtras = new Bundle(); 1328 if (mCropValue.equals("circle")) { 1329 newExtras.putString("circleCrop", "true"); 1330 } 1331 if (mSaveUri != null) { 1332 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri); 1333 } else { 1334 newExtras.putBoolean("return-data", true); 1335 } 1336 1337 Intent cropIntent = new Intent("com.android.camera.action.CROP"); 1338 1339 cropIntent.setData(tempUri); 1340 cropIntent.putExtras(newExtras); 1341 1342 startActivityForResult(cropIntent, CROP_MSG); 1343 } 1344 } 1345 1346 private void doCancel() { 1347 setResultEx(RESULT_CANCELED, new Intent()); 1348 finish(); 1349 } 1350 1351 @Override 1352 public void onShutterButtonFocus(boolean pressed) { 1353 if (mPausing || collapseCameraControls() || mCameraState == SNAPSHOT_IN_PROGRESS) return; 1354 1355 // Do not do focus if there is not enough storage. 1356 if (pressed && !canTakePicture()) return; 1357 1358 // Lock AE and AWB so users can half-press shutter and recompose. 1359 mAeAwbLock = pressed; 1360 if (mAeAwbLock && (mAeLockSupported || mAwbLockSupported)) { 1361 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1362 } 1363 1364 mFocusManager.doFocus(pressed); 1365 1366 // Unlock AE and AWB after cancelAutoFocus. Camera API does not 1367 // guarantee setParameters can be called during autofocus. 1368 if (!mAeAwbLock && (mAeLockSupported || mAwbLockSupported)) { 1369 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1370 } 1371 } 1372 1373 @Override 1374 public void onShutterButtonClick() { 1375 if (mPausing || collapseCameraControls()) return; 1376 1377 // Do not take the picture if there is not enough storage. 1378 if (mPicturesRemaining <= 0) { 1379 Log.i(TAG, "Not enough space or storage not ready. remaining=" + mPicturesRemaining); 1380 return; 1381 } 1382 1383 Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState); 1384 1385 // If the user wants to do a snapshot while the previous one is still 1386 // in progress, remember the fact and do it after we finish the previous 1387 // one and re-start the preview. 1388 if (mCameraState == SNAPSHOT_IN_PROGRESS) { 1389 mSnapshotOnIdle = true; 1390 return; 1391 } 1392 1393 mSnapshotOnIdle = false; 1394 mFocusManager.doSnap(); 1395 } 1396 1397 @Override 1398 public void onShutterButtonLongPressed() { 1399 if (mPausing || mCameraState == SNAPSHOT_IN_PROGRESS 1400 || mCameraDevice == null || mPicturesRemaining <= 0) return; 1401 1402 Log.v(TAG, "onShutterButtonLongPressed"); 1403 mFocusManager.shutterLongPressed(); 1404 } 1405 1406 private OnScreenHint mStorageHint; 1407 1408 private void updateStorageHint() { 1409 String noStorageText = null; 1410 1411 if (mPicturesRemaining == Storage.UNAVAILABLE) { 1412 noStorageText = getString(R.string.no_storage); 1413 } else if (mPicturesRemaining == Storage.PREPARING) { 1414 noStorageText = getString(R.string.preparing_sd); 1415 } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) { 1416 noStorageText = getString(R.string.access_sd_fail); 1417 } else if (mPicturesRemaining < 1L) { 1418 noStorageText = getString(R.string.not_enough_space); 1419 } 1420 1421 if (noStorageText != null) { 1422 if (mStorageHint == null) { 1423 mStorageHint = OnScreenHint.makeText(this, noStorageText); 1424 } else { 1425 mStorageHint.setText(noStorageText); 1426 } 1427 mStorageHint.show(); 1428 } else if (mStorageHint != null) { 1429 mStorageHint.cancel(); 1430 mStorageHint = null; 1431 } 1432 } 1433 1434 private void installIntentFilter() { 1435 // install an intent filter to receive SD card related events. 1436 IntentFilter intentFilter = 1437 new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); 1438 intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); 1439 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); 1440 intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); 1441 intentFilter.addDataScheme("file"); 1442 registerReceiver(mReceiver, intentFilter); 1443 mDidRegister = true; 1444 } 1445 1446 @Override 1447 protected void onResume() { 1448 super.onResume(); 1449 mPausing = false; 1450 if (mOpenCameraFail || mCameraDisabled) return; 1451 1452 mJpegPictureCallbackTime = 0; 1453 mZoomValue = 0; 1454 1455 // Start the preview if it is not started. 1456 if (mCameraState == PREVIEW_STOPPED) { 1457 try { 1458 mCameraDevice = Util.openCamera(this, mCameraId); 1459 initializeCapabilities(); 1460 resetExposureCompensation(); 1461 startPreview(); 1462 } catch (CameraHardwareException e) { 1463 Util.showErrorAndFinish(this, R.string.cannot_connect_camera); 1464 return; 1465 } catch (CameraDisabledException e) { 1466 Util.showErrorAndFinish(this, R.string.camera_disabled); 1467 return; 1468 } 1469 } 1470 1471 if (mSurfaceHolder != null) { 1472 // If first time initialization is not finished, put it in the 1473 // message queue. 1474 if (!mFirstTimeInitialized) { 1475 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1476 } else { 1477 initializeSecondTime(); 1478 } 1479 } 1480 keepScreenOnAwhile(); 1481 1482 if (mCameraState == IDLE) { 1483 mOnResumeTime = SystemClock.uptimeMillis(); 1484 mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); 1485 } 1486 } 1487 1488 @Override 1489 protected void onPause() { 1490 mPausing = true; 1491 stopPreview(); 1492 // Close the camera now because other activities may need to use it. 1493 closeCamera(); 1494 resetScreenOn(); 1495 1496 // Clear UI. 1497 collapseCameraControls(); 1498 if (mSharePopup != null) mSharePopup.dismiss(); 1499 if (mFaceView != null) mFaceView.clear(); 1500 1501 if (mFirstTimeInitialized) { 1502 mOrientationListener.disable(); 1503 mImageSaver.finish(); 1504 mImageSaver = null; 1505 if (!mIsImageCaptureIntent && mThumbnail != null && !mThumbnail.fromFile()) { 1506 mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME)); 1507 } 1508 } 1509 1510 if (mDidRegister) { 1511 unregisterReceiver(mReceiver); 1512 mDidRegister = false; 1513 } 1514 if (mLocationManager != null) mLocationManager.recordLocation(false); 1515 updateExposureOnScreenIndicator(0); 1516 1517 mFocusManager.releaseSoundPlayer(); 1518 1519 if (mStorageHint != null) { 1520 mStorageHint.cancel(); 1521 mStorageHint = null; 1522 } 1523 1524 // If we are in an image capture intent and has taken 1525 // a picture, we just clear it in onPause. 1526 mJpegImageData = null; 1527 1528 // Remove the messages in the event queue. 1529 mHandler.removeMessages(FIRST_TIME_INIT); 1530 mHandler.removeMessages(CHECK_DISPLAY_ROTATION); 1531 mFocusManager.removeMessages(); 1532 1533 super.onPause(); 1534 } 1535 1536 @Override 1537 protected void onActivityResult( 1538 int requestCode, int resultCode, Intent data) { 1539 switch (requestCode) { 1540 case CROP_MSG: { 1541 Intent intent = new Intent(); 1542 if (data != null) { 1543 Bundle extras = data.getExtras(); 1544 if (extras != null) { 1545 intent.putExtras(extras); 1546 } 1547 } 1548 setResultEx(resultCode, intent); 1549 finish(); 1550 1551 File path = getFileStreamPath(sTempCropFilename); 1552 path.delete(); 1553 1554 break; 1555 } 1556 } 1557 } 1558 1559 private boolean canTakePicture() { 1560 return isCameraIdle() && (mPicturesRemaining > 0); 1561 } 1562 1563 @Override 1564 public void autoFocus() { 1565 mFocusStartTime = System.currentTimeMillis(); 1566 mCameraDevice.autoFocus(mAutoFocusCallback); 1567 mCameraState = FOCUSING; 1568 enableCameraControls(false); 1569 } 1570 1571 @Override 1572 public void cancelAutoFocus() { 1573 mCameraDevice.cancelAutoFocus(); 1574 mCameraState = IDLE; 1575 enableCameraControls(true); 1576 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1577 } 1578 1579 // Preview area is touched. Handle touch focus. 1580 @Override 1581 public boolean onTouch(View v, MotionEvent e) { 1582 if (mPausing || mCameraDevice == null || !mFirstTimeInitialized 1583 || mCameraState == SNAPSHOT_IN_PROGRESS) { 1584 return false; 1585 } 1586 1587 // Do not trigger touch focus if popup window is opened. 1588 if (collapseCameraControls()) return false; 1589 1590 // Check if metering area or focus area is supported. 1591 if (!mFocusAreaSupported && !mMeteringAreaSupported) return false; 1592 1593 return mFocusManager.onTouch(e); 1594 } 1595 1596 @Override 1597 public void onBackPressed() { 1598 if (!isCameraIdle()) { 1599 // ignore backs while we're taking a picture 1600 return; 1601 } else if (!collapseCameraControls()) { 1602 super.onBackPressed(); 1603 } 1604 } 1605 1606 @Override 1607 public boolean onKeyDown(int keyCode, KeyEvent event) { 1608 switch (keyCode) { 1609 case KeyEvent.KEYCODE_FOCUS: 1610 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1611 onShutterButtonFocus(true); 1612 } 1613 return true; 1614 case KeyEvent.KEYCODE_CAMERA: 1615 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1616 onShutterButtonClick(); 1617 } 1618 return true; 1619 case KeyEvent.KEYCODE_DPAD_CENTER: 1620 // If we get a dpad center event without any focused view, move 1621 // the focus to the shutter button and press it. 1622 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1623 // Start auto-focus immediately to reduce shutter lag. After 1624 // the shutter button gets the focus, onShutterButtonFocus() 1625 // will be called again but it is fine. 1626 if (collapseCameraControls()) return true; 1627 onShutterButtonFocus(true); 1628 if (mShutterButton.isInTouchMode()) { 1629 mShutterButton.requestFocusFromTouch(); 1630 } else { 1631 mShutterButton.requestFocus(); 1632 } 1633 mShutterButton.setPressed(true); 1634 } 1635 return true; 1636 } 1637 1638 return super.onKeyDown(keyCode, event); 1639 } 1640 1641 @Override 1642 public boolean onKeyUp(int keyCode, KeyEvent event) { 1643 switch (keyCode) { 1644 case KeyEvent.KEYCODE_FOCUS: 1645 if (mFirstTimeInitialized) { 1646 onShutterButtonFocus(false); 1647 } 1648 return true; 1649 } 1650 return super.onKeyUp(keyCode, event); 1651 } 1652 1653 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1654 // Make sure we have a surface in the holder before proceeding. 1655 if (holder.getSurface() == null) { 1656 Log.d(TAG, "holder.getSurface() == null"); 1657 return; 1658 } 1659 1660 Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h); 1661 1662 // We need to save the holder for later use, even when the mCameraDevice 1663 // is null. This could happen if onResume() is invoked after this 1664 // function. 1665 mSurfaceHolder = holder; 1666 1667 // The mCameraDevice will be null if it fails to connect to the camera 1668 // hardware. In this case we will show a dialog and then finish the 1669 // activity, so it's OK to ignore it. 1670 if (mCameraDevice == null) return; 1671 1672 // Sometimes surfaceChanged is called after onPause or before onResume. 1673 // Ignore it. 1674 if (mPausing || isFinishing()) return; 1675 1676 // Set preview display if the surface is being created. Preview was 1677 // already started. Also restart the preview if display rotation has 1678 // changed. Sometimes this happens when the device is held in portrait 1679 // and camera app is opened. Rotation animation takes some time and 1680 // display rotation in onCreate may not be what we want. 1681 if (mCameraState == PREVIEW_STOPPED) { 1682 startPreview(); 1683 } else { 1684 if (Util.getDisplayRotation(this) != mDisplayRotation) { 1685 setDisplayOrientation(); 1686 } 1687 if (holder.isCreating()) { 1688 // Set preview display if the surface is being created and preview 1689 // was already started. That means preview display was set to null 1690 // and we need to set it now. 1691 setPreviewDisplay(holder); 1692 } 1693 } 1694 1695 // If first time initialization is not finished, send a message to do 1696 // it later. We want to finish surfaceChanged as soon as possible to let 1697 // user see preview first. 1698 if (!mFirstTimeInitialized) { 1699 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1700 } else { 1701 initializeSecondTime(); 1702 } 1703 } 1704 1705 public void surfaceCreated(SurfaceHolder holder) { 1706 } 1707 1708 public void surfaceDestroyed(SurfaceHolder holder) { 1709 stopPreview(); 1710 mSurfaceHolder = null; 1711 } 1712 1713 private void closeCamera() { 1714 if (mCameraDevice != null) { 1715 CameraHolder.instance().release(); 1716 mCameraDevice.setZoomChangeListener(null); 1717 mCameraDevice.setFaceDetectionListener(null); 1718 mCameraDevice.setErrorCallback(null); 1719 mCameraDevice = null; 1720 mCameraState = PREVIEW_STOPPED; 1721 mFocusManager.onCameraReleased(); 1722 } 1723 } 1724 1725 private void setPreviewDisplay(SurfaceHolder holder) { 1726 try { 1727 mCameraDevice.setPreviewDisplay(holder); 1728 } catch (Throwable ex) { 1729 closeCamera(); 1730 throw new RuntimeException("setPreviewDisplay failed", ex); 1731 } 1732 } 1733 1734 private void setDisplayOrientation() { 1735 mDisplayRotation = Util.getDisplayRotation(this); 1736 mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId); 1737 mCameraDevice.setDisplayOrientation(mDisplayOrientation); 1738 if (mFaceView != null) { 1739 mFaceView.setDisplayOrientation(mDisplayOrientation); 1740 } 1741 } 1742 1743 private void startPreview() { 1744 if (mPausing || isFinishing()) return; 1745 1746 mFocusManager.resetTouchFocus(); 1747 1748 mCameraDevice.setErrorCallback(mErrorCallback); 1749 1750 // If we're previewing already, stop the preview first (this will blank 1751 // the screen). 1752 if (mCameraState != PREVIEW_STOPPED) stopPreview(); 1753 1754 setPreviewDisplay(mSurfaceHolder); 1755 setDisplayOrientation(); 1756 mAeAwbLock = false; // Unlock AE and AWB. 1757 setCameraParameters(UPDATE_PARAM_ALL); 1758 // If the focus mode is continuous autofocus, call cancelAutoFocus to 1759 // resume it because it may have been paused by autoFocus call. 1760 if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mParameters.getFocusMode())) { 1761 mCameraDevice.cancelAutoFocus(); 1762 } 1763 1764 // Inform the mainthread to go on the UI initialization. 1765 if (mCameraPreviewThread != null) { 1766 synchronized (mCameraPreviewThread) { 1767 mCameraPreviewThread.notify(); 1768 } 1769 } 1770 1771 try { 1772 Log.v(TAG, "startPreview"); 1773 mCameraDevice.startPreview(); 1774 } catch (Throwable ex) { 1775 closeCamera(); 1776 throw new RuntimeException("startPreview failed", ex); 1777 } 1778 1779 startFaceDetection(); 1780 mZoomState = ZOOM_STOPPED; 1781 mCameraState = IDLE; 1782 mFocusManager.onPreviewStarted(); 1783 1784 if (mSnapshotOnIdle) { 1785 mHandler.post(mDoSnapRunnable); 1786 } 1787 } 1788 1789 private void stopPreview() { 1790 if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { 1791 Log.v(TAG, "stopPreview"); 1792 mCameraDevice.cancelAutoFocus(); // Reset the focus. 1793 mCameraDevice.stopPreview(); 1794 } 1795 mCameraState = PREVIEW_STOPPED; 1796 mFocusManager.onPreviewStopped(); 1797 } 1798 1799 private static boolean isSupported(String value, List<String> supported) { 1800 return supported == null ? false : supported.indexOf(value) >= 0; 1801 } 1802 1803 private void updateCameraParametersInitialize() { 1804 // Reset preview frame rate to the maximum because it may be lowered by 1805 // video camera application. 1806 List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); 1807 if (frameRates != null) { 1808 Integer max = Collections.max(frameRates); 1809 mParameters.setPreviewFrameRate(max); 1810 } 1811 1812 mParameters.setRecordingHint(false); 1813 1814 // Disable video stabilization. Convenience methods not available in API 1815 // level <= 14 1816 String vstabSupported = mParameters.get("video-stabilization-supported"); 1817 if ("true".equals(vstabSupported)) { 1818 mParameters.set("video-stabilization", "false"); 1819 } 1820 } 1821 1822 private void updateCameraParametersZoom() { 1823 // Set zoom. 1824 if (mParameters.isZoomSupported()) { 1825 mParameters.setZoom(mZoomValue); 1826 } 1827 } 1828 1829 private void updateCameraParametersPreference() { 1830 if (mAeLockSupported) { 1831 mParameters.setAutoExposureLock(mAeAwbLock); 1832 } 1833 1834 if (mAwbLockSupported) { 1835 mParameters.setAutoWhiteBalanceLock(mAeAwbLock); 1836 } 1837 1838 if (mFocusAreaSupported) { 1839 mParameters.setFocusAreas(mFocusManager.getFocusAreas()); 1840 } 1841 1842 if (mMeteringAreaSupported) { 1843 // Use the same area for focus and metering. 1844 mParameters.setMeteringAreas(mFocusManager.getMeteringAreas()); 1845 } 1846 1847 // Set picture size. 1848 String pictureSize = mPreferences.getString( 1849 CameraSettings.KEY_PICTURE_SIZE, null); 1850 if (pictureSize == null) { 1851 CameraSettings.initialCameraPictureSize(this, mParameters); 1852 } else { 1853 List<Size> supported = mParameters.getSupportedPictureSizes(); 1854 CameraSettings.setCameraPictureSize( 1855 pictureSize, supported, mParameters); 1856 } 1857 1858 // Set the preview frame aspect ratio according to the picture size. 1859 Size size = mParameters.getPictureSize(); 1860 1861 mPreviewPanel = findViewById(R.id.frame_layout); 1862 mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame); 1863 mPreviewFrameLayout.setAspectRatio((double) size.width / size.height); 1864 1865 // Set a preview size that is closest to the viewfinder height and has 1866 // the right aspect ratio. 1867 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 1868 Size optimalSize = Util.getOptimalPreviewSize(this, 1869 sizes, (double) size.width / size.height); 1870 Size original = mParameters.getPreviewSize(); 1871 if (!original.equals(optimalSize)) { 1872 mParameters.setPreviewSize(optimalSize.width, optimalSize.height); 1873 1874 // Zoom related settings will be changed for different preview 1875 // sizes, so set and read the parameters to get lastest values 1876 mCameraDevice.setParameters(mParameters); 1877 mParameters = mCameraDevice.getParameters(); 1878 } 1879 Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); 1880 1881 // Since change scene mode may change supported values, 1882 // Set scene mode first, 1883 mSceneMode = mPreferences.getString( 1884 CameraSettings.KEY_SCENE_MODE, 1885 getString(R.string.pref_camera_scenemode_default)); 1886 if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { 1887 if (!mParameters.getSceneMode().equals(mSceneMode)) { 1888 mParameters.setSceneMode(mSceneMode); 1889 mCameraDevice.setParameters(mParameters); 1890 1891 // Setting scene mode will change the settings of flash mode, 1892 // white balance, and focus mode. Here we read back the 1893 // parameters, so we can know those settings. 1894 mParameters = mCameraDevice.getParameters(); 1895 } 1896 } else { 1897 mSceneMode = mParameters.getSceneMode(); 1898 if (mSceneMode == null) { 1899 mSceneMode = Parameters.SCENE_MODE_AUTO; 1900 } 1901 } 1902 1903 // Set JPEG quality. 1904 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, 1905 CameraProfile.QUALITY_HIGH); 1906 mParameters.setJpegQuality(jpegQuality); 1907 1908 // For the following settings, we need to check if the settings are 1909 // still supported by latest driver, if not, ignore the settings. 1910 1911 // Set exposure compensation 1912 int value = CameraSettings.readExposure(mPreferences); 1913 int max = mParameters.getMaxExposureCompensation(); 1914 int min = mParameters.getMinExposureCompensation(); 1915 if (value >= min && value <= max) { 1916 mParameters.setExposureCompensation(value); 1917 } else { 1918 Log.w(TAG, "invalid exposure range: " + value); 1919 } 1920 1921 if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 1922 // Set flash mode. 1923 String flashMode = mPreferences.getString( 1924 CameraSettings.KEY_FLASH_MODE, 1925 getString(R.string.pref_camera_flashmode_default)); 1926 List<String> supportedFlash = mParameters.getSupportedFlashModes(); 1927 if (isSupported(flashMode, supportedFlash)) { 1928 mParameters.setFlashMode(flashMode); 1929 } else { 1930 flashMode = mParameters.getFlashMode(); 1931 if (flashMode == null) { 1932 flashMode = getString( 1933 R.string.pref_camera_flashmode_no_flash); 1934 } 1935 } 1936 1937 // Set white balance parameter. 1938 String whiteBalance = mPreferences.getString( 1939 CameraSettings.KEY_WHITE_BALANCE, 1940 getString(R.string.pref_camera_whitebalance_default)); 1941 if (isSupported(whiteBalance, 1942 mParameters.getSupportedWhiteBalance())) { 1943 mParameters.setWhiteBalance(whiteBalance); 1944 } else { 1945 whiteBalance = mParameters.getWhiteBalance(); 1946 if (whiteBalance == null) { 1947 whiteBalance = Parameters.WHITE_BALANCE_AUTO; 1948 } 1949 } 1950 1951 // Set focus mode. 1952 mFocusManager.overrideFocusMode(null); 1953 mParameters.setFocusMode(mFocusManager.getFocusMode()); 1954 } else { 1955 mFocusManager.overrideFocusMode(mParameters.getFocusMode()); 1956 } 1957 } 1958 1959 // We separate the parameters into several subsets, so we can update only 1960 // the subsets actually need updating. The PREFERENCE set needs extra 1961 // locking because the preference can be changed from GLThread as well. 1962 private void setCameraParameters(int updateSet) { 1963 mParameters = mCameraDevice.getParameters(); 1964 1965 if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) { 1966 updateCameraParametersInitialize(); 1967 } 1968 1969 if ((updateSet & UPDATE_PARAM_ZOOM) != 0) { 1970 updateCameraParametersZoom(); 1971 } 1972 1973 if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) { 1974 updateCameraParametersPreference(); 1975 } 1976 1977 mCameraDevice.setParameters(mParameters); 1978 } 1979 1980 // If the Camera is idle, update the parameters immediately, otherwise 1981 // accumulate them in mUpdateSet and update later. 1982 private void setCameraParametersWhenIdle(int additionalUpdateSet) { 1983 mUpdateSet |= additionalUpdateSet; 1984 if (mCameraDevice == null) { 1985 // We will update all the parameters when we open the device, so 1986 // we don't need to do anything now. 1987 mUpdateSet = 0; 1988 return; 1989 } else if (isCameraIdle()) { 1990 setCameraParameters(mUpdateSet); 1991 updateSceneModeUI(); 1992 mUpdateSet = 0; 1993 } else { 1994 if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) { 1995 mHandler.sendEmptyMessageDelayed( 1996 SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000); 1997 } 1998 } 1999 } 2000 2001 private void gotoGallery() { 2002 MenuHelper.gotoCameraImageGallery(this); 2003 } 2004 2005 private boolean isCameraIdle() { 2006 return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted()); 2007 } 2008 2009 private boolean isImageCaptureIntent() { 2010 String action = getIntent().getAction(); 2011 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); 2012 } 2013 2014 private void setupCaptureParams() { 2015 Bundle myExtras = getIntent().getExtras(); 2016 if (myExtras != null) { 2017 mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 2018 mCropValue = myExtras.getString("crop"); 2019 } 2020 } 2021 2022 private void showPostCaptureAlert() { 2023 if (mIsImageCaptureIntent) { 2024 Util.fadeOut(mIndicatorControlContainer); 2025 Util.fadeOut(mShutterButton); 2026 2027 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2028 for (int id : pickIds) { 2029 Util.fadeIn(findViewById(id)); 2030 } 2031 } 2032 } 2033 2034 private void hidePostCaptureAlert() { 2035 if (mIsImageCaptureIntent) { 2036 enableCameraControls(true); 2037 2038 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2039 for (int id : pickIds) { 2040 Util.fadeOut(findViewById(id)); 2041 } 2042 2043 Util.fadeIn(mShutterButton); 2044 Util.fadeIn(mIndicatorControlContainer); 2045 } 2046 } 2047 2048 @Override 2049 public boolean onPrepareOptionsMenu(Menu menu) { 2050 super.onPrepareOptionsMenu(menu); 2051 // Only show the menu when camera is idle. 2052 for (int i = 0; i < menu.size(); i++) { 2053 menu.getItem(i).setVisible(isCameraIdle()); 2054 } 2055 2056 return true; 2057 } 2058 2059 @Override 2060 public boolean onCreateOptionsMenu(Menu menu) { 2061 super.onCreateOptionsMenu(menu); 2062 2063 if (mIsImageCaptureIntent) { 2064 // No options menu for attach mode. 2065 return false; 2066 } else { 2067 addBaseMenuItems(menu); 2068 } 2069 return true; 2070 } 2071 2072 private void addBaseMenuItems(Menu menu) { 2073 MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() { 2074 public void run() { 2075 switchToOtherMode(ModePicker.MODE_VIDEO); 2076 } 2077 }); 2078 MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() { 2079 public void run() { 2080 switchToOtherMode(ModePicker.MODE_PANORAMA); 2081 } 2082 }); 2083 2084 if (mNumberOfCameras > 1) { 2085 menu.add(R.string.switch_camera_id) 2086 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2087 public boolean onMenuItemClick(MenuItem item) { 2088 CameraSettings.writePreferredCameraId(mPreferences, 2089 ((mCameraId == mFrontCameraId) 2090 ? mBackCameraId : mFrontCameraId)); 2091 onSharedPreferenceChanged(); 2092 return true; 2093 } 2094 }).setIcon(android.R.drawable.ic_menu_camera); 2095 } 2096 } 2097 2098 private boolean switchToOtherMode(int mode) { 2099 if (isFinishing()) return false; 2100 if (mImageSaver != null) mImageSaver.waitDone(); 2101 MenuHelper.gotoMode(mode, Camera.this); 2102 mHandler.removeMessages(FIRST_TIME_INIT); 2103 finish(); 2104 return true; 2105 } 2106 2107 public boolean onModeChanged(int mode) { 2108 if (mode != ModePicker.MODE_CAMERA) { 2109 return switchToOtherMode(mode); 2110 } else { 2111 return true; 2112 } 2113 } 2114 2115 public void onSharedPreferenceChanged() { 2116 // ignore the events after "onPause()" 2117 if (mPausing) return; 2118 2119 boolean recordLocation = RecordLocationPreference.get( 2120 mPreferences, getContentResolver()); 2121 mLocationManager.recordLocation(recordLocation); 2122 2123 int cameraId = CameraSettings.readPreferredCameraId(mPreferences); 2124 if (mCameraId != cameraId) { 2125 // Restart the activity to have a crossfade animation. 2126 // TODO: Use SurfaceTexture to implement a better and faster 2127 // animation. 2128 if (mIsImageCaptureIntent) { 2129 // If the intent is camera capture, stay in camera capture mode. 2130 MenuHelper.gotoCameraMode(this, getIntent()); 2131 } else { 2132 MenuHelper.gotoCameraMode(this); 2133 } 2134 2135 finish(); 2136 } else { 2137 setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE); 2138 } 2139 2140 int exposureValue = CameraSettings.readExposure(mPreferences); 2141 updateExposureOnScreenIndicator(exposureValue); 2142 } 2143 2144 @Override 2145 public void onUserInteraction() { 2146 super.onUserInteraction(); 2147 keepScreenOnAwhile(); 2148 } 2149 2150 private void resetScreenOn() { 2151 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2152 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2153 } 2154 2155 private void keepScreenOnAwhile() { 2156 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2157 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2158 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 2159 } 2160 2161 public void onRestorePreferencesClicked() { 2162 if (mPausing) return; 2163 Runnable runnable = new Runnable() { 2164 public void run() { 2165 restorePreferences(); 2166 } 2167 }; 2168 MenuHelper.confirmAction(this, 2169 getString(R.string.confirm_restore_title), 2170 getString(R.string.confirm_restore_message), 2171 runnable); 2172 } 2173 2174 private void restorePreferences() { 2175 // Reset the zoom. Zoom value is not stored in preference. 2176 if (mParameters.isZoomSupported()) { 2177 mZoomValue = 0; 2178 setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM); 2179 mZoomControl.setZoomIndex(0); 2180 } 2181 if (mIndicatorControlContainer != null) { 2182 mIndicatorControlContainer.dismissSettingPopup(); 2183 CameraSettings.restorePreferences(Camera.this, mPreferences, 2184 mParameters); 2185 mIndicatorControlContainer.reloadPreferences(); 2186 onSharedPreferenceChanged(); 2187 } 2188 } 2189 2190 public void onOverriddenPreferencesClicked() { 2191 if (mPausing) return; 2192 if (mNotSelectableToast == null) { 2193 String str = getResources().getString(R.string.not_selectable_in_scene_mode); 2194 mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT); 2195 } 2196 mNotSelectableToast.show(); 2197 } 2198 2199 private void showSharePopup() { 2200 mImageSaver.waitDone(); 2201 Uri uri = mThumbnail.getUri(); 2202 if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) { 2203 // SharePopup window takes the mPreviewPanel as its size reference. 2204 mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(), 2205 mOrientationCompensation, mPreviewPanel); 2206 } 2207 mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0); 2208 } 2209 2210 @Override 2211 public void onFaceDetection(Face[] faces, android.hardware.Camera camera) { 2212 mFaceView.setFaces(faces); 2213 } 2214 2215 private void showTapToFocusToast() { 2216 // Show the toast. 2217 RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt); 2218 v.setOrientation(mOrientationCompensation); 2219 v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter)); 2220 v.setVisibility(View.VISIBLE); 2221 mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000); 2222 // Clear the preference. 2223 Editor editor = mPreferences.edit(); 2224 editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false); 2225 editor.apply(); 2226 } 2227 2228 private void initializeCapabilities() { 2229 mInitialParams = mCameraDevice.getParameters(); 2230 mFocusManager.initializeParameters(mInitialParams); 2231 mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0 2232 && isSupported(Parameters.FOCUS_MODE_AUTO, 2233 mInitialParams.getSupportedFocusModes())); 2234 mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0); 2235 mAeLockSupported = mInitialParams.isAutoExposureLockSupported(); 2236 mAwbLockSupported = mInitialParams.isAutoWhiteBalanceLockSupported(); 2237 } 2238} 2239