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