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