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