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