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