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