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