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