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