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