Camera.java revision 750173a4d20f1e8d6607edb3ada6be5166d0cd82
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 Button zoomIncrement = (Button) findViewById(R.id.zoom_increment); 609 Button zoomDecrement = (Button) 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 sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri)); 872 } 873 } else { 874 mJpegImageData = data; 875 if (!mQuickCapture) { 876 showPostCaptureAlert(); 877 } else { 878 doAttach(); 879 } 880 } 881 } 882 883 private void capture() { 884 // If we are already in the middle of taking a snapshot then ignore. 885 if (mPausing || mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) { 886 return; 887 } 888 mCaptureStartTime = System.currentTimeMillis(); 889 mPostViewPictureCallbackTime = 0; 890 enableCameraControls(false); 891 mJpegImageData = null; 892 893 // See android.hardware.Camera.Parameters.setRotation for 894 // documentation. 895 int rotation = 0; 896 if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) { 897 CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; 898 if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 899 rotation = (info.orientation - mOrientation + 360) % 360; 900 } else { // back-facing camera 901 rotation = (info.orientation + mOrientation) % 360; 902 } 903 } 904 mParameters.setRotation(rotation); 905 906 // Clear previous GPS location from the parameters. 907 mParameters.removeGpsData(); 908 909 // We always encode GpsTimeStamp 910 mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000); 911 912 // Set GPS location. 913 Location loc = mRecordLocation ? getCurrentLocation() : null; 914 if (loc != null) { 915 double lat = loc.getLatitude(); 916 double lon = loc.getLongitude(); 917 boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); 918 919 if (hasLatLon) { 920 Log.d(TAG, "Set gps location"); 921 mParameters.setGpsLatitude(lat); 922 mParameters.setGpsLongitude(lon); 923 mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase()); 924 if (loc.hasAltitude()) { 925 mParameters.setGpsAltitude(loc.getAltitude()); 926 } else { 927 // for NETWORK_PROVIDER location provider, we may have 928 // no altitude information, but the driver needs it, so 929 // we fake one. 930 mParameters.setGpsAltitude(0); 931 } 932 if (loc.getTime() != 0) { 933 // Location.getTime() is UTC in milliseconds. 934 // gps-timestamp is UTC in seconds. 935 long utcTimeSeconds = loc.getTime() / 1000; 936 mParameters.setGpsTimestamp(utcTimeSeconds); 937 } 938 } else { 939 loc = null; 940 } 941 } 942 943 mCameraDevice.setParameters(mParameters); 944 945 mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, 946 mPostViewPictureCallback, new JpegPictureCallback(loc)); 947 mCameraState = SNAPSHOT_IN_PROGRESS; 948 mHandler.removeMessages(RESET_TOUCH_FOCUS); 949 } 950 951 private boolean saveDataToFile(String filePath, byte[] data) { 952 FileOutputStream f = null; 953 try { 954 f = new FileOutputStream(filePath); 955 f.write(data); 956 } catch (IOException e) { 957 return false; 958 } finally { 959 Util.closeSilently(f); 960 } 961 return true; 962 } 963 964 private String createName(long dateTaken) { 965 Date date = new Date(dateTaken); 966 SimpleDateFormat dateFormat = new SimpleDateFormat( 967 getString(R.string.image_file_name_format)); 968 969 return dateFormat.format(date); 970 } 971 972 @Override 973 public void onCreate(Bundle icicle) { 974 super.onCreate(icicle); 975 976 mIsImageCaptureIntent = isImageCaptureIntent(); 977 if (mIsImageCaptureIntent) { 978 setContentView(R.layout.camera_attach); 979 } else { 980 setContentView(R.layout.camera); 981 } 982 mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle); 983 mShareButton = findViewById(R.id.share_button); 984 mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail); 985 mShareIcon = (RotateImageView) findViewById(R.id.share_icon); 986 mCameraSwitchIcon = (RotateImageView) findViewById(R.id.camera_switch_icon); 987 mVideoSwitchIcon = (RotateImageView) findViewById(R.id.video_switch_icon); 988 989 mPreferences = new ComboPreferences(this); 990 CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal()); 991 992 mCameraId = CameraSettings.readPreferredCameraId(mPreferences); 993 994 // Testing purpose. Launch a specific camera through the intent extras. 995 int intentCameraId = Util.getCameraFacingIntentExtras(this); 996 if (intentCameraId != -1) { 997 mCameraId = intentCameraId; 998 } 999 1000 mPreferences.setLocalId(this, mCameraId); 1001 CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); 1002 1003 mNumberOfCameras = CameraHolder.instance().getNumberOfCameras(); 1004 mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); 1005 1006 // we need to reset exposure for the preview 1007 resetExposureCompensation(); 1008 1009 /* 1010 * To reduce startup time, we start the preview in another thread. 1011 * We make sure the preview is started at the end of onCreate. 1012 */ 1013 Thread startPreviewThread = new Thread(new Runnable() { 1014 public void run() { 1015 try { 1016 mCameraDevice = Util.openCamera(Camera.this, mCameraId); 1017 mInitialParams = mCameraDevice.getParameters(); 1018 startPreview(); 1019 } catch (CameraHardwareException e) { 1020 mOpenCameraFail = true; 1021 } catch (CameraDisabledException e) { 1022 mCameraDisabled = true; 1023 } 1024 } 1025 }); 1026 startPreviewThread.start(); 1027 1028 // don't set mSurfaceHolder here. We have it set ONLY within 1029 // surfaceChanged / surfaceDestroyed, other parts of the code 1030 // assume that when it is set, the surface is also set. 1031 SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview); 1032 SurfaceHolder holder = preview.getHolder(); 1033 holder.addCallback(this); 1034 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 1035 1036 if (mIsImageCaptureIntent) { 1037 setupCaptureParams(); 1038 1039 findViewById(R.id.review_control).setVisibility(View.VISIBLE); 1040 findViewById(R.id.btn_cancel).setOnClickListener(this); 1041 findViewById(R.id.btn_retake).setOnClickListener(this); 1042 findViewById(R.id.btn_done).setOnClickListener(this); 1043 } else { 1044 mSwitcher = (SwitcherSet) findViewById(R.id.camera_switch); 1045 mSwitcher.setVisibility(View.VISIBLE); 1046 mSwitcher.setOnSwitchListener(this); 1047 mSwitcher.setSwitch(SWITCH_CAMERA); 1048 } 1049 1050 // Make sure preview is started. 1051 try { 1052 startPreviewThread.join(); 1053 if (mOpenCameraFail) { 1054 Util.showErrorAndFinish(this, R.string.cannot_connect_camera); 1055 return; 1056 } else if (mCameraDisabled) { 1057 Util.showErrorAndFinish(this, R.string.camera_disabled); 1058 return; 1059 } 1060 } catch (InterruptedException ex) { 1061 // ignore 1062 } 1063 1064 mBackCameraId = CameraHolder.instance().getBackCameraId(); 1065 mFrontCameraId = CameraHolder.instance().getFrontCameraId(); 1066 1067 // Do this after starting preview because it depends on camera 1068 // parameters. 1069 initializeIndicatorWheel(); 1070 initializeCameraPicker(); 1071 initializeZoomPicker(); 1072 } 1073 1074 private void changeHeadUpDisplayState() { 1075 if (mHeadUpDisplay == null) return; 1076 // If the camera resumes behind the lock screen, the orientation 1077 // will be portrait. That causes OOM when we try to allocation GPU 1078 // memory for the GLSurfaceView again when the orientation changes. So, 1079 // we delayed initialization of HeadUpDisplay until the orientation 1080 // becomes landscape. 1081 Configuration config = getResources().getConfiguration(); 1082 if (config.orientation == Configuration.ORIENTATION_LANDSCAPE 1083 && !mPausing && mFirstTimeInitialized) { 1084 if (mGLRootView == null) attachHeadUpDisplay(); 1085 } else if (mGLRootView != null) { 1086 detachHeadUpDisplay(); 1087 } 1088 } 1089 1090 private void overrideCameraSettings(final String flashMode, 1091 final String whiteBalance, final String focusMode) { 1092 if (mHeadUpDisplay != null) { 1093 mHeadUpDisplay.overrideSettings( 1094 CameraSettings.KEY_FLASH_MODE, flashMode, 1095 CameraSettings.KEY_WHITE_BALANCE, whiteBalance, 1096 CameraSettings.KEY_FOCUS_MODE, focusMode); 1097 } 1098 if (mIndicatorWheel != null) { 1099 mIndicatorWheel.overrideSettings( 1100 CameraSettings.KEY_FLASH_MODE, flashMode, 1101 CameraSettings.KEY_WHITE_BALANCE, whiteBalance, 1102 CameraSettings.KEY_FOCUS_MODE, focusMode); 1103 } 1104 } 1105 1106 private void updateSceneModeUI() { 1107 // If scene mode is set, we cannot set flash mode, white balance, and 1108 // focus mode, instead, we read it from driver 1109 if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 1110 overrideCameraSettings(mParameters.getFlashMode(), 1111 mParameters.getWhiteBalance(), mParameters.getFocusMode()); 1112 } else { 1113 overrideCameraSettings(null, null, null); 1114 } 1115 } 1116 1117 private void loadCameraPreferences() { 1118 CameraSettings settings = new CameraSettings(this, mInitialParams, 1119 mCameraId, CameraHolder.instance().getCameraInfo()); 1120 mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences); 1121 } 1122 1123 private void initializeIndicatorWheel() { 1124 mIndicatorWheel = (IndicatorWheel) findViewById(R.id.indicator_wheel); 1125 if (mIndicatorWheel == null) return; 1126 loadCameraPreferences(); 1127 1128 final String[] SETTING_KEYS = { 1129 CameraSettings.KEY_FLASH_MODE}; 1130 final String[] OTHER_SETTING_KEYS = { 1131 CameraSettings.KEY_WHITE_BALANCE, 1132 CameraSettings.KEY_COLOR_EFFECT, 1133 CameraSettings.KEY_SCENE_MODE, 1134 CameraSettings.KEY_RECORD_LOCATION, 1135 CameraSettings.KEY_FOCUS_MODE, 1136 CameraSettings.KEY_EXPOSURE, 1137 CameraSettings.KEY_PICTURE_SIZE}; 1138 mIndicatorWheel.initialize(this, mPreferenceGroup, SETTING_KEYS, 1139 OTHER_SETTING_KEYS); 1140 mIndicatorWheel.setListener(new MyIndicatorWheelListener()); 1141 mPopupGestureDetector = new GestureDetector(this, 1142 new PopupGestureListener()); 1143 updateSceneModeUI(); 1144 } 1145 1146 private void initializeHeadUpDisplay() { 1147 if (mHeadUpDisplay == null) return; 1148 loadCameraPreferences(); 1149 1150 float[] zoomRatios = null; 1151 if(mParameters.isZoomSupported()) { 1152 zoomRatios = Util.convertZoomRatios(mParameters.getZoomRatios()); 1153 } 1154 mHeadUpDisplay.initialize(this, mPreferenceGroup, 1155 zoomRatios, mOrientationCompensation); 1156 if (mParameters.isZoomSupported()) { 1157 mHeadUpDisplay.setZoomListener(new ZoomControllerListener() { 1158 public void onZoomChanged( 1159 int index, float ratio, boolean isMoving) { 1160 onZoomValueChanged(index); 1161 } 1162 }); 1163 } 1164 updateSceneModeUI(); 1165 } 1166 1167 private void attachHeadUpDisplay() { 1168 mHeadUpDisplay.setOrientation(mOrientationCompensation); 1169 if (mParameters.isZoomSupported()) { 1170 mHeadUpDisplay.setZoomIndex(mZoomValue); 1171 } 1172 ViewGroup frame = (ViewGroup) findViewById(R.id.frame); 1173 mGLRootView = new GLRootView(this); 1174 mGLRootView.setContentPane(mHeadUpDisplay); 1175 frame.addView(mGLRootView); 1176 } 1177 1178 private void detachHeadUpDisplay() { 1179 mHeadUpDisplay.collapse(); 1180 ((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView); 1181 mGLRootView = null; 1182 } 1183 1184 private boolean collapseCameraControls() { 1185 if (mHeadUpDisplay != null && mHeadUpDisplay.collapse()) { 1186 return true; 1187 } 1188 if (mIndicatorWheel != null && mIndicatorWheel.dismissSettingPopup()) { 1189 return true; 1190 } 1191 return false; 1192 } 1193 1194 private void enableCameraControls(boolean enable) { 1195 if (mHeadUpDisplay != null) mHeadUpDisplay.setEnabled(enable); 1196 if (mIndicatorWheel != null) mIndicatorWheel.setEnabled(enable); 1197 if (mCameraPicker != null) mCameraPicker.setEnabled(enable); 1198 if (mZoomPicker != null) mZoomPicker.setEnabled(enable); 1199 if (mSwitcher != null) mSwitcher.setEnabled(enable); 1200 } 1201 1202 public static int roundOrientation(int orientation) { 1203 return ((orientation + 45) / 90 * 90) % 360; 1204 } 1205 1206 private class MyOrientationEventListener 1207 extends OrientationEventListener { 1208 public MyOrientationEventListener(Context context) { 1209 super(context); 1210 } 1211 1212 @Override 1213 public void onOrientationChanged(int orientation) { 1214 // We keep the last known orientation. So if the user first orient 1215 // the camera then point the camera to floor or sky, we still have 1216 // the correct orientation. 1217 if (orientation == ORIENTATION_UNKNOWN) return; 1218 mOrientation = roundOrientation(orientation); 1219 // When the screen is unlocked, display rotation may change. Always 1220 // calculate the up-to-date orientationCompensation. 1221 int orientationCompensation = mOrientation 1222 + Util.getDisplayRotation(Camera.this); 1223 if (mOrientationCompensation != orientationCompensation) { 1224 mOrientationCompensation = orientationCompensation; 1225 if (!mIsImageCaptureIntent) { 1226 setOrientationIndicator(mOrientationCompensation); 1227 } 1228 } 1229 } 1230 } 1231 1232 private void setOrientationIndicator(int degree) { 1233 if (mHeadUpDisplay != null) mHeadUpDisplay.setOrientation(mOrientationCompensation); 1234 if (mThumbnailView != null) mThumbnailView.setDegree(degree); 1235 if (mShareIcon != null) mShareIcon.setDegree(degree); 1236 if (mCameraSwitchIcon != null) mCameraSwitchIcon.setDegree(degree); 1237 if (mVideoSwitchIcon != null) mVideoSwitchIcon.setDegree(degree); 1238 if (mSharePopup != null) mSharePopup.setOrientation(degree); 1239 } 1240 1241 @Override 1242 public void onStop() { 1243 super.onStop(); 1244 if (mMediaProviderClient != null) { 1245 mMediaProviderClient.release(); 1246 mMediaProviderClient = null; 1247 } 1248 } 1249 1250 private void checkStorage() { 1251 mPicturesRemaining = Storage.getAvailableSpace(); 1252 if (mPicturesRemaining > 0) { 1253 mPicturesRemaining /= 1500000; 1254 } 1255 updateStorageHint(); 1256 } 1257 1258 @Override 1259 public void onClick(View v) { 1260 switch (v.getId()) { 1261 case R.id.share_button: 1262 if (isCameraIdle() && mThumbnail != null) { 1263 showSharePopup(); 1264 } 1265 break; 1266 case R.id.btn_retake: 1267 hidePostCaptureAlert(); 1268 startPreview(); 1269 break; 1270 case R.id.btn_done: 1271 doAttach(); 1272 break; 1273 case R.id.btn_cancel: 1274 doCancel(); 1275 break; 1276 } 1277 } 1278 1279 private void doAttach() { 1280 if (mPausing) { 1281 return; 1282 } 1283 1284 byte[] data = mJpegImageData; 1285 1286 if (mCropValue == null) { 1287 // First handle the no crop case -- just return the value. If the 1288 // caller specifies a "save uri" then write the data to it's 1289 // stream. Otherwise, pass back a scaled down version of the bitmap 1290 // directly in the extras. 1291 if (mSaveUri != null) { 1292 OutputStream outputStream = null; 1293 try { 1294 outputStream = mContentResolver.openOutputStream(mSaveUri); 1295 outputStream.write(data); 1296 outputStream.close(); 1297 1298 setResultEx(RESULT_OK); 1299 finish(); 1300 } catch (IOException ex) { 1301 // ignore exception 1302 } finally { 1303 Util.closeSilently(outputStream); 1304 } 1305 } else { 1306 int orientation = Exif.getOrientation(data); 1307 Bitmap bitmap = Util.makeBitmap(data, 50 * 1024); 1308 bitmap = Util.rotate(bitmap, orientation); 1309 setResultEx(RESULT_OK, 1310 new Intent("inline-data").putExtra("data", bitmap)); 1311 finish(); 1312 } 1313 } else { 1314 // Save the image to a temp file and invoke the cropper 1315 Uri tempUri = null; 1316 FileOutputStream tempStream = null; 1317 try { 1318 File path = getFileStreamPath(sTempCropFilename); 1319 path.delete(); 1320 tempStream = openFileOutput(sTempCropFilename, 0); 1321 tempStream.write(data); 1322 tempStream.close(); 1323 tempUri = Uri.fromFile(path); 1324 } catch (FileNotFoundException ex) { 1325 setResultEx(Activity.RESULT_CANCELED); 1326 finish(); 1327 return; 1328 } catch (IOException ex) { 1329 setResultEx(Activity.RESULT_CANCELED); 1330 finish(); 1331 return; 1332 } finally { 1333 Util.closeSilently(tempStream); 1334 } 1335 1336 Bundle newExtras = new Bundle(); 1337 if (mCropValue.equals("circle")) { 1338 newExtras.putString("circleCrop", "true"); 1339 } 1340 if (mSaveUri != null) { 1341 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri); 1342 } else { 1343 newExtras.putBoolean("return-data", true); 1344 } 1345 1346 Intent cropIntent = new Intent("com.android.camera.action.CROP"); 1347 1348 cropIntent.setData(tempUri); 1349 cropIntent.putExtras(newExtras); 1350 1351 startActivityForResult(cropIntent, CROP_MSG); 1352 } 1353 } 1354 1355 private void doCancel() { 1356 setResultEx(RESULT_CANCELED, new Intent()); 1357 finish(); 1358 } 1359 1360 public void onShutterButtonFocus(ShutterButton button, boolean pressed) { 1361 if (mPausing) { 1362 return; 1363 } 1364 switch (button.getId()) { 1365 case R.id.shutter_button: 1366 doFocus(pressed); 1367 break; 1368 } 1369 } 1370 1371 public void onShutterButtonClick(ShutterButton button) { 1372 if (mPausing) { 1373 return; 1374 } 1375 switch (button.getId()) { 1376 case R.id.shutter_button: 1377 doSnap(); 1378 break; 1379 } 1380 } 1381 1382 private OnScreenHint mStorageHint; 1383 1384 private void updateStorageHint() { 1385 String noStorageText = null; 1386 1387 if (mPicturesRemaining == Storage.UNAVAILABLE) { 1388 noStorageText = getString(R.string.no_storage); 1389 } else if (mPicturesRemaining == Storage.PREPARING) { 1390 noStorageText = getString(R.string.preparing_sd); 1391 } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) { 1392 noStorageText = getString(R.string.access_sd_fail); 1393 } else if (mPicturesRemaining < 1L) { 1394 noStorageText = getString(R.string.not_enough_space); 1395 } 1396 1397 if (noStorageText != null) { 1398 if (mStorageHint == null) { 1399 mStorageHint = OnScreenHint.makeText(this, noStorageText); 1400 } else { 1401 mStorageHint.setText(noStorageText); 1402 } 1403 mStorageHint.show(); 1404 } else if (mStorageHint != null) { 1405 mStorageHint.cancel(); 1406 mStorageHint = null; 1407 } 1408 } 1409 1410 private void installIntentFilter() { 1411 // install an intent filter to receive SD card related events. 1412 IntentFilter intentFilter = 1413 new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); 1414 intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); 1415 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); 1416 intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); 1417 intentFilter.addDataScheme("file"); 1418 registerReceiver(mReceiver, intentFilter); 1419 mDidRegister = true; 1420 } 1421 1422 private void initializeFocusTone() { 1423 // Initialize focus tone generator. 1424 try { 1425 mFocusToneGenerator = new ToneGenerator( 1426 AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); 1427 } catch (Throwable ex) { 1428 Log.w(TAG, "Exception caught while creating tone generator: ", ex); 1429 mFocusToneGenerator = null; 1430 } 1431 } 1432 1433 private void initializeScreenBrightness() { 1434 Window win = getWindow(); 1435 // Overright the brightness settings if it is automatic 1436 int mode = Settings.System.getInt( 1437 getContentResolver(), 1438 Settings.System.SCREEN_BRIGHTNESS_MODE, 1439 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); 1440 if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { 1441 WindowManager.LayoutParams winParams = win.getAttributes(); 1442 winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS; 1443 win.setAttributes(winParams); 1444 } 1445 } 1446 1447 @Override 1448 protected void onResume() { 1449 super.onResume(); 1450 mPausing = false; 1451 if (mOpenCameraFail || mCameraDisabled) return; 1452 1453 mJpegPictureCallbackTime = 0; 1454 mZoomValue = 0; 1455 1456 // Start the preview if it is not started. 1457 if (mCameraState == PREVIEW_STOPPED) { 1458 try { 1459 mCameraDevice = Util.openCamera(this, mCameraId); 1460 mInitialParams = mCameraDevice.getParameters(); 1461 resetExposureCompensation(); 1462 startPreview(); 1463 } catch(CameraHardwareException e) { 1464 Util.showErrorAndFinish(this, R.string.cannot_connect_camera); 1465 return; 1466 } catch(CameraDisabledException e) { 1467 Util.showErrorAndFinish(this, R.string.camera_disabled); 1468 return; 1469 } 1470 } 1471 1472 if (mSurfaceHolder != null) { 1473 // If first time initialization is not finished, put it in the 1474 // message queue. 1475 if (!mFirstTimeInitialized) { 1476 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1477 } else { 1478 initializeSecondTime(); 1479 } 1480 } 1481 keepScreenOnAwhile(); 1482 1483 if (mCameraState == IDLE) { 1484 mOnResumeTime = SystemClock.uptimeMillis(); 1485 mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); 1486 } 1487 } 1488 1489 @Override 1490 public void onConfigurationChanged(Configuration config) { 1491 super.onConfigurationChanged(config); 1492 changeHeadUpDisplayState(); 1493 } 1494 1495 @Override 1496 protected void onPause() { 1497 mPausing = true; 1498 stopPreview(); 1499 // Close the camera now because other activities may need to use it. 1500 closeCamera(); 1501 resetScreenOn(); 1502 collapseCameraControls(); 1503 changeHeadUpDisplayState(); 1504 1505 if (mFirstTimeInitialized) { 1506 mOrientationListener.disable(); 1507 if (!mIsImageCaptureIntent) { 1508 if (mThumbnail != null) { 1509 mThumbnail.saveTo(new File(getFilesDir(), LAST_THUMB_FILENAME)); 1510 } 1511 } 1512 hidePostCaptureAlert(); 1513 } 1514 1515 if (mSharePopup != null) mSharePopup.dismiss(); 1516 1517 if (mDidRegister) { 1518 unregisterReceiver(mReceiver); 1519 mDidRegister = false; 1520 } 1521 stopReceivingLocationUpdates(); 1522 1523 if (mFocusToneGenerator != null) { 1524 mFocusToneGenerator.release(); 1525 mFocusToneGenerator = null; 1526 } 1527 1528 if (mStorageHint != null) { 1529 mStorageHint.cancel(); 1530 mStorageHint = null; 1531 } 1532 1533 // If we are in an image capture intent and has taken 1534 // a picture, we just clear it in onPause. 1535 mJpegImageData = null; 1536 1537 // Remove the messages in the event queue. 1538 mHandler.removeMessages(RESTART_PREVIEW); 1539 mHandler.removeMessages(FIRST_TIME_INIT); 1540 mHandler.removeMessages(CHECK_DISPLAY_ROTATION); 1541 mHandler.removeMessages(RESET_TOUCH_FOCUS); 1542 1543 super.onPause(); 1544 } 1545 1546 @Override 1547 protected void onActivityResult( 1548 int requestCode, int resultCode, Intent data) { 1549 switch (requestCode) { 1550 case CROP_MSG: { 1551 Intent intent = new Intent(); 1552 if (data != null) { 1553 Bundle extras = data.getExtras(); 1554 if (extras != null) { 1555 intent.putExtras(extras); 1556 } 1557 } 1558 setResultEx(resultCode, intent); 1559 finish(); 1560 1561 File path = getFileStreamPath(sTempCropFilename); 1562 path.delete(); 1563 1564 break; 1565 } 1566 } 1567 } 1568 1569 private boolean canTakePicture() { 1570 return isCameraIdle() && (mPicturesRemaining > 0); 1571 } 1572 1573 private void autoFocus() { 1574 Log.v(TAG, "Start autofocus."); 1575 mFocusStartTime = System.currentTimeMillis(); 1576 mCameraDevice.autoFocus(mAutoFocusCallback); 1577 mCameraState = FOCUSING; 1578 enableCameraControls(false); 1579 updateFocusUI(); 1580 mHandler.removeMessages(RESET_TOUCH_FOCUS); 1581 } 1582 1583 private void cancelAutoFocus() { 1584 Log.v(TAG, "Cancel autofocus."); 1585 mCameraDevice.cancelAutoFocus(); 1586 mCameraState = IDLE; 1587 enableCameraControls(true); 1588 resetTouchFocus(); 1589 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1590 updateFocusUI(); 1591 mHandler.removeMessages(RESET_TOUCH_FOCUS); 1592 } 1593 1594 private void updateFocusUI() { 1595 if (mCameraState == FOCUSING || mCameraState == FOCUSING_SNAP_ON_FINISH) { 1596 mFocusRectangle.showStart(); 1597 } else if (mCameraState == FOCUS_SUCCESS) { 1598 mFocusRectangle.showSuccess(); 1599 } else if (mCameraState == FOCUS_FAIL) { 1600 mFocusRectangle.showFail(); 1601 } else if (mCameraState == IDLE && mFocusArea != null) { 1602 // Users touch on the preview and the rectangle indicates the metering area. 1603 // Either focus area is not supported or autoFocus call is not required. 1604 mFocusRectangle.showStart(); 1605 } else { 1606 mFocusRectangle.clear(); 1607 } 1608 } 1609 1610 // Preview area is touched. Handle touch focus. 1611 @Override 1612 public boolean onTouch(View v, MotionEvent e) { 1613 if (mPausing || !mFirstTimeInitialized || mCameraState == SNAPSHOT_IN_PROGRESS 1614 || mCameraState == FOCUSING_SNAP_ON_FINISH) { 1615 return false; 1616 } 1617 1618 // Do not trigger touch focus if popup window is opened. 1619 if (collapseCameraControls()) return false; 1620 1621 // Check if metering area or focus area is supported. 1622 boolean focusAreaSupported = (mParameters.getMaxNumFocusAreas() > 0 1623 && (mFocusMode.equals(Parameters.FOCUS_MODE_AUTO) || 1624 mFocusMode.equals(Parameters.FOCUS_MODE_MACRO) || 1625 mFocusMode.equals(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))); 1626 boolean meteringAreaSupported = (mParameters.getMaxNumMeteringAreas() > 0); 1627 if (!focusAreaSupported && !meteringAreaSupported) return false; 1628 1629 boolean callAutoFocusRequired = false; 1630 if (focusAreaSupported && 1631 (mFocusMode.equals(Parameters.FOCUS_MODE_AUTO) || 1632 mFocusMode.equals(Parameters.FOCUS_MODE_MACRO))) { 1633 callAutoFocusRequired = true; 1634 } 1635 1636 // Let users be able to cancel previous touch focus. 1637 if (callAutoFocusRequired && mFocusArea != null && e.getAction() == MotionEvent.ACTION_DOWN 1638 && (mCameraState == FOCUSING || mCameraState == FOCUS_SUCCESS || 1639 mCameraState == FOCUS_FAIL)) { 1640 cancelAutoFocus(); 1641 } 1642 1643 // Initialize variables. 1644 int x = Math.round(e.getX()); 1645 int y = Math.round(e.getY()); 1646 int focusWidth = mFocusRectangle.getWidth(); 1647 int focusHeight = mFocusRectangle.getHeight(); 1648 int previewWidth = mPreviewFrame.getWidth(); 1649 int previewHeight = mPreviewFrame.getHeight(); 1650 if (mFocusArea == null) { 1651 mFocusArea = new ArrayList<Area>(); 1652 mFocusArea.add(new Area(new Rect(), 1)); 1653 } 1654 1655 // Convert the coordinates to driver format. The actual focus area is two times bigger than 1656 // UI because a huge rectangle looks strange. 1657 int areaWidth = focusWidth * 2; 1658 int areaHeight = focusHeight * 2; 1659 int areaLeft = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth); 1660 int areaTop = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight); 1661 Log.d(TAG, "x=" + x + ". y=" + y); 1662 Log.d(TAG, "Focus area left=" + areaLeft + ". top=" + areaTop); 1663 Log.d(TAG, "Preview width=" + previewWidth + ". height=" + previewHeight); 1664 Log.d(TAG, "focusWidth=" + focusWidth + ". focusHeight=" + focusHeight); 1665 Rect rect = mFocusArea.get(0).rect; 1666 convertToFocusArea(areaLeft, areaTop, areaWidth, areaHeight, previewWidth, previewHeight, 1667 mFocusArea.get(0).rect); 1668 1669 // Use margin to set the focus rectangle to the touched area. 1670 RelativeLayout.LayoutParams p = 1671 (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams(); 1672 int left = Util.clamp(x - focusWidth / 2, 0, previewWidth - focusWidth); 1673 int top = Util.clamp(y - focusHeight / 2, 0, previewHeight - focusHeight); 1674 p.setMargins(left, top, 0, 0); 1675 // Disable "center" rule because we no longer want to put it in the center. 1676 int[] rules = p.getRules(); 1677 rules[RelativeLayout.CENTER_IN_PARENT] = 0; 1678 mFocusRectangle.requestLayout(); 1679 1680 // Set the focus area and metering area. 1681 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1682 if (callAutoFocusRequired && e.getAction() == MotionEvent.ACTION_UP) { 1683 autoFocus(); 1684 } else { // Just show the rectangle in all other cases. 1685 updateFocusUI(); 1686 // Reset the metering area in 3 seconds. 1687 mHandler.removeMessages(RESET_TOUCH_FOCUS); 1688 mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY); 1689 } 1690 1691 return true; 1692 } 1693 1694 // Convert the touch point to the focus area in driver format. 1695 public static void convertToFocusArea(int left, int top, int focusWidth, int focusHeight, 1696 int previewWidth, int previewHeight, Rect rect) { 1697 rect.left = Math.round((float) left / previewWidth * 2000 - 1000); 1698 rect.top = Math.round((float) top / previewHeight * 2000 - 1000); 1699 rect.right = Math.round((float) (left + focusWidth) / previewWidth * 2000 - 1000); 1700 rect.bottom = Math.round((float) (top + focusHeight) / previewHeight * 2000 - 1000); 1701 } 1702 1703 void resetTouchFocus() { 1704 // Put focus rectangle to the center. 1705 RelativeLayout.LayoutParams p = 1706 (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams(); 1707 int[] rules = p.getRules(); 1708 rules[RelativeLayout.CENTER_IN_PARENT] = RelativeLayout.TRUE; 1709 p.setMargins(0, 0, 0, 0); 1710 1711 mFocusArea = null; 1712 } 1713 1714 @Override 1715 public void onBackPressed() { 1716 if (!isCameraIdle()) { 1717 // ignore backs while we're taking a picture 1718 return; 1719 } else if (!collapseCameraControls()) { 1720 super.onBackPressed(); 1721 } 1722 } 1723 1724 @Override 1725 public boolean onKeyDown(int keyCode, KeyEvent event) { 1726 switch (keyCode) { 1727 case KeyEvent.KEYCODE_FOCUS: 1728 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1729 doFocus(true); 1730 } 1731 return true; 1732 case KeyEvent.KEYCODE_CAMERA: 1733 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1734 doSnap(); 1735 } 1736 return true; 1737 case KeyEvent.KEYCODE_DPAD_CENTER: 1738 // If we get a dpad center event without any focused view, move 1739 // the focus to the shutter button and press it. 1740 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1741 // Start auto-focus immediately to reduce shutter lag. After 1742 // the shutter button gets the focus, doFocus() will be 1743 // called again but it is fine. 1744 if (collapseCameraControls()) return true; 1745 doFocus(true); 1746 if (mShutterButton.isInTouchMode()) { 1747 mShutterButton.requestFocusFromTouch(); 1748 } else { 1749 mShutterButton.requestFocus(); 1750 } 1751 mShutterButton.setPressed(true); 1752 } 1753 return true; 1754 } 1755 1756 return super.onKeyDown(keyCode, event); 1757 } 1758 1759 @Override 1760 public boolean onKeyUp(int keyCode, KeyEvent event) { 1761 switch (keyCode) { 1762 case KeyEvent.KEYCODE_FOCUS: 1763 if (mFirstTimeInitialized) { 1764 doFocus(false); 1765 } 1766 return true; 1767 } 1768 return super.onKeyUp(keyCode, event); 1769 } 1770 1771 private void doSnap() { 1772 if (collapseCameraControls()) return; 1773 1774 Log.v(TAG, "doSnap: mCameraState=" + mCameraState); 1775 // If the user has half-pressed the shutter and focus is completed, we 1776 // can take the photo right away. If the focus mode is infinity, we can 1777 // also take the photo. 1778 if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY) 1779 || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED) 1780 || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF) 1781 || (mCameraState == FOCUS_SUCCESS 1782 || mCameraState == FOCUS_FAIL)) { 1783 capture(); 1784 } else if (mCameraState == FOCUSING) { 1785 // Half pressing the shutter (i.e. the focus button event) will 1786 // already have requested AF for us, so just request capture on 1787 // focus here. 1788 mCameraState = FOCUSING_SNAP_ON_FINISH; 1789 } else if (mCameraState == IDLE) { 1790 // Focus key down event is dropped for some reasons. Just ignore. 1791 } 1792 } 1793 1794 private void doFocus(boolean pressed) { 1795 // Do the focus if the mode is not infinity. 1796 if (collapseCameraControls()) return; 1797 if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY) 1798 || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED) 1799 || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) { 1800 if (pressed) { // Focus key down. 1801 // Do not do focus if there is not enoguh storage. Do not focus 1802 // if touch focus has been triggered, that is, camera state is 1803 // FOCUS_SUCCESS or FOCUS_FAIL. 1804 if (canTakePicture() && mCameraState != FOCUS_SUCCESS 1805 && mCameraState != FOCUS_FAIL) { 1806 autoFocus(); 1807 } 1808 } else { // Focus key up. 1809 // User releases half-pressed focus key. 1810 if (mCameraState == FOCUSING || mCameraState == FOCUS_SUCCESS 1811 || mCameraState == FOCUS_FAIL) { 1812 cancelAutoFocus(); 1813 } 1814 } 1815 } 1816 } 1817 1818 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1819 // Make sure we have a surface in the holder before proceeding. 1820 if (holder.getSurface() == null) { 1821 Log.d(TAG, "holder.getSurface() == null"); 1822 return; 1823 } 1824 1825 Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h); 1826 1827 // We need to save the holder for later use, even when the mCameraDevice 1828 // is null. This could happen if onResume() is invoked after this 1829 // function. 1830 mSurfaceHolder = holder; 1831 1832 // The mCameraDevice will be null if it fails to connect to the camera 1833 // hardware. In this case we will show a dialog and then finish the 1834 // activity, so it's OK to ignore it. 1835 if (mCameraDevice == null) return; 1836 1837 // Sometimes surfaceChanged is called after onPause or before onResume. 1838 // Ignore it. 1839 if (mPausing || isFinishing()) return; 1840 1841 // Set preview display if the surface is being created. Preview was 1842 // already started. Also restart the preview if display rotation has 1843 // changed. Sometimes this happens when the device is held in portrait 1844 // and camera app is opened. Rotation animation takes some time and 1845 // display rotation in onCreate may not be what we want. 1846 if (mCameraState != PREVIEW_STOPPED 1847 && (Util.getDisplayRotation(this) == mDisplayRotation) 1848 && holder.isCreating()) { 1849 // Set preview display if the surface is being created and preview 1850 // was already started. That means preview display was set to null 1851 // and we need to set it now. 1852 setPreviewDisplay(holder); 1853 } else { 1854 // 1. Restart the preview if the size of surface was changed. The 1855 // framework may not support changing preview display on the fly. 1856 // 2. Start the preview now if surface was destroyed and preview 1857 // stopped. 1858 startPreview(); 1859 } 1860 1861 // If first time initialization is not finished, send a message to do 1862 // it later. We want to finish surfaceChanged as soon as possible to let 1863 // user see preview first. 1864 if (!mFirstTimeInitialized) { 1865 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1866 } else { 1867 initializeSecondTime(); 1868 } 1869 } 1870 1871 public void surfaceCreated(SurfaceHolder holder) { 1872 } 1873 1874 public void surfaceDestroyed(SurfaceHolder holder) { 1875 stopPreview(); 1876 mSurfaceHolder = null; 1877 } 1878 1879 private void closeCamera() { 1880 if (mCameraDevice != null) { 1881 CameraHolder.instance().release(); 1882 mCameraDevice.setZoomChangeListener(null); 1883 mCameraDevice = null; 1884 mCameraState = PREVIEW_STOPPED; 1885 } 1886 } 1887 1888 private void setPreviewDisplay(SurfaceHolder holder) { 1889 try { 1890 mCameraDevice.setPreviewDisplay(holder); 1891 } catch (Throwable ex) { 1892 closeCamera(); 1893 throw new RuntimeException("setPreviewDisplay failed", ex); 1894 } 1895 } 1896 1897 private void startPreview() { 1898 if (mPausing || isFinishing()) return; 1899 1900 resetTouchFocus(); 1901 1902 mCameraDevice.setErrorCallback(mErrorCallback); 1903 1904 // If we're previewing already, stop the preview first (this will blank 1905 // the screen). 1906 if (mCameraState != PREVIEW_STOPPED) stopPreview(); 1907 1908 setPreviewDisplay(mSurfaceHolder); 1909 mDisplayRotation = Util.getDisplayRotation(this); 1910 Util.setCameraDisplayOrientation(mDisplayRotation, mCameraId, mCameraDevice); 1911 setCameraParameters(UPDATE_PARAM_ALL); 1912 1913 1914 try { 1915 Log.v(TAG, "startPreview"); 1916 mCameraDevice.startPreview(); 1917 } catch (Throwable ex) { 1918 closeCamera(); 1919 throw new RuntimeException("startPreview failed", ex); 1920 } 1921 mZoomState = ZOOM_STOPPED; 1922 mCameraState = IDLE; 1923 } 1924 1925 private void stopPreview() { 1926 if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { 1927 Log.v(TAG, "stopPreview"); 1928 mCameraDevice.stopPreview(); 1929 } 1930 mCameraState = PREVIEW_STOPPED; 1931 // If auto focus was in progress, it would have been canceled. 1932 updateFocusUI(); 1933 } 1934 1935 private static boolean isSupported(String value, List<String> supported) { 1936 return supported == null ? false : supported.indexOf(value) >= 0; 1937 } 1938 1939 private void updateCameraParametersInitialize() { 1940 // Reset preview frame rate to the maximum because it may be lowered by 1941 // video camera application. 1942 List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); 1943 if (frameRates != null) { 1944 Integer max = Collections.max(frameRates); 1945 mParameters.setPreviewFrameRate(max); 1946 } 1947 1948 } 1949 1950 private void updateCameraParametersZoom() { 1951 // Set zoom. 1952 if (mParameters.isZoomSupported()) { 1953 mParameters.setZoom(mZoomValue); 1954 } 1955 } 1956 1957 private void updateCameraParametersPreference() { 1958 if (mParameters.getMaxNumFocusAreas() > 0) { 1959 mParameters.setFocusAreas(mFocusArea); 1960 Log.d(TAG, "Parameter focus areas=" + mParameters.get("focus-areas")); 1961 } 1962 1963 if (mParameters.getMaxNumMeteringAreas() > 0) { 1964 // Use the same area for focus and metering. 1965 mParameters.setMeteringAreas(mFocusArea); 1966 } 1967 1968 // Set picture size. 1969 String pictureSize = mPreferences.getString( 1970 CameraSettings.KEY_PICTURE_SIZE, null); 1971 if (pictureSize == null) { 1972 CameraSettings.initialCameraPictureSize(this, mParameters); 1973 } else { 1974 List<Size> supported = mParameters.getSupportedPictureSizes(); 1975 CameraSettings.setCameraPictureSize( 1976 pictureSize, supported, mParameters); 1977 } 1978 1979 // Set the preview frame aspect ratio according to the picture size. 1980 Size size = mParameters.getPictureSize(); 1981 PreviewFrameLayout frameLayout = 1982 (PreviewFrameLayout) findViewById(R.id.frame_layout); 1983 frameLayout.setAspectRatio((double) size.width / size.height); 1984 1985 // Set a preview size that is closest to the viewfinder height and has 1986 // the right aspect ratio. 1987 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 1988 Size optimalSize = Util.getOptimalPreviewSize(this, 1989 sizes, (double) size.width / size.height); 1990 Size original = mParameters.getPreviewSize(); 1991 if (!original.equals(optimalSize)) { 1992 mParameters.setPreviewSize(optimalSize.width, optimalSize.height); 1993 1994 // Zoom related settings will be changed for different preview 1995 // sizes, so set and read the parameters to get lastest values 1996 mCameraDevice.setParameters(mParameters); 1997 mParameters = mCameraDevice.getParameters(); 1998 } 1999 Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); 2000 2001 // Since change scene mode may change supported values, 2002 // Set scene mode first, 2003 mSceneMode = mPreferences.getString( 2004 CameraSettings.KEY_SCENE_MODE, 2005 getString(R.string.pref_camera_scenemode_default)); 2006 if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { 2007 if (!mParameters.getSceneMode().equals(mSceneMode)) { 2008 mParameters.setSceneMode(mSceneMode); 2009 mCameraDevice.setParameters(mParameters); 2010 2011 // Setting scene mode will change the settings of flash mode, 2012 // white balance, and focus mode. Here we read back the 2013 // parameters, so we can know those settings. 2014 mParameters = mCameraDevice.getParameters(); 2015 } 2016 } else { 2017 mSceneMode = mParameters.getSceneMode(); 2018 if (mSceneMode == null) { 2019 mSceneMode = Parameters.SCENE_MODE_AUTO; 2020 } 2021 } 2022 2023 // Set JPEG quality. 2024 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, 2025 CameraProfile.QUALITY_HIGH); 2026 mParameters.setJpegQuality(jpegQuality); 2027 2028 // For the following settings, we need to check if the settings are 2029 // still supported by latest driver, if not, ignore the settings. 2030 2031 // Set color effect parameter. 2032 String colorEffect = mPreferences.getString( 2033 CameraSettings.KEY_COLOR_EFFECT, 2034 getString(R.string.pref_camera_coloreffect_default)); 2035 if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) { 2036 mParameters.setColorEffect(colorEffect); 2037 } 2038 2039 // Set exposure compensation 2040 String exposure = mPreferences.getString( 2041 CameraSettings.KEY_EXPOSURE, 2042 getString(R.string.pref_exposure_default)); 2043 try { 2044 int value = Integer.parseInt(exposure); 2045 int max = mParameters.getMaxExposureCompensation(); 2046 int min = mParameters.getMinExposureCompensation(); 2047 if (value >= min && value <= max) { 2048 mParameters.setExposureCompensation(value); 2049 } else { 2050 Log.w(TAG, "invalid exposure range: " + exposure); 2051 } 2052 } catch (NumberFormatException e) { 2053 Log.w(TAG, "invalid exposure: " + exposure); 2054 } 2055 2056 if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 2057 // Set flash mode. 2058 String flashMode = mPreferences.getString( 2059 CameraSettings.KEY_FLASH_MODE, 2060 getString(R.string.pref_camera_flashmode_default)); 2061 List<String> supportedFlash = mParameters.getSupportedFlashModes(); 2062 if (isSupported(flashMode, supportedFlash)) { 2063 mParameters.setFlashMode(flashMode); 2064 } else { 2065 flashMode = mParameters.getFlashMode(); 2066 if (flashMode == null) { 2067 flashMode = getString( 2068 R.string.pref_camera_flashmode_no_flash); 2069 } 2070 } 2071 2072 // Set white balance parameter. 2073 String whiteBalance = mPreferences.getString( 2074 CameraSettings.KEY_WHITE_BALANCE, 2075 getString(R.string.pref_camera_whitebalance_default)); 2076 if (isSupported(whiteBalance, 2077 mParameters.getSupportedWhiteBalance())) { 2078 mParameters.setWhiteBalance(whiteBalance); 2079 } else { 2080 whiteBalance = mParameters.getWhiteBalance(); 2081 if (whiteBalance == null) { 2082 whiteBalance = Parameters.WHITE_BALANCE_AUTO; 2083 } 2084 } 2085 2086 // Set focus mode. 2087 mFocusMode = mPreferences.getString( 2088 CameraSettings.KEY_FOCUS_MODE, 2089 getString(R.string.pref_camera_focusmode_default)); 2090 if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) { 2091 mParameters.setFocusMode(mFocusMode); 2092 } else { 2093 mFocusMode = mParameters.getFocusMode(); 2094 if (mFocusMode == null) { 2095 mFocusMode = Parameters.FOCUS_MODE_AUTO; 2096 } 2097 } 2098 } else { 2099 mFocusMode = mParameters.getFocusMode(); 2100 } 2101 } 2102 2103 // We separate the parameters into several subsets, so we can update only 2104 // the subsets actually need updating. The PREFERENCE set needs extra 2105 // locking because the preference can be changed from GLThread as well. 2106 private void setCameraParameters(int updateSet) { 2107 mParameters = mCameraDevice.getParameters(); 2108 2109 if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) { 2110 updateCameraParametersInitialize(); 2111 } 2112 2113 if ((updateSet & UPDATE_PARAM_ZOOM) != 0) { 2114 updateCameraParametersZoom(); 2115 } 2116 2117 if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) { 2118 updateCameraParametersPreference(); 2119 } 2120 2121 mCameraDevice.setParameters(mParameters); 2122 } 2123 2124 // If the Camera is idle, update the parameters immediately, otherwise 2125 // accumulate them in mUpdateSet and update later. 2126 private void setCameraParametersWhenIdle(int additionalUpdateSet) { 2127 mUpdateSet |= additionalUpdateSet; 2128 if (mCameraDevice == null) { 2129 // We will update all the parameters when we open the device, so 2130 // we don't need to do anything now. 2131 mUpdateSet = 0; 2132 return; 2133 } else if (isCameraIdle()) { 2134 setCameraParameters(mUpdateSet); 2135 updateSceneModeUI(); 2136 mUpdateSet = 0; 2137 } else { 2138 if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) { 2139 mHandler.sendEmptyMessageDelayed( 2140 SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000); 2141 } 2142 } 2143 } 2144 2145 private void gotoGallery() { 2146 MenuHelper.gotoCameraImageGallery(this); 2147 } 2148 2149 private void startReceivingLocationUpdates() { 2150 if (mLocationManager != null) { 2151 try { 2152 mLocationManager.requestLocationUpdates( 2153 LocationManager.NETWORK_PROVIDER, 2154 1000, 2155 0F, 2156 mLocationListeners[1]); 2157 } catch (SecurityException ex) { 2158 Log.i(TAG, "fail to request location update, ignore", ex); 2159 } catch (IllegalArgumentException ex) { 2160 Log.d(TAG, "provider does not exist " + ex.getMessage()); 2161 } 2162 try { 2163 mLocationManager.requestLocationUpdates( 2164 LocationManager.GPS_PROVIDER, 2165 1000, 2166 0F, 2167 mLocationListeners[0]); 2168 showGpsOnScreenIndicator(false); 2169 } catch (SecurityException ex) { 2170 Log.i(TAG, "fail to request location update, ignore", ex); 2171 } catch (IllegalArgumentException ex) { 2172 Log.d(TAG, "provider does not exist " + ex.getMessage()); 2173 } 2174 Log.d(TAG, "startReceivingLocationUpdates"); 2175 } 2176 } 2177 2178 private void stopReceivingLocationUpdates() { 2179 if (mLocationManager != null) { 2180 for (int i = 0; i < mLocationListeners.length; i++) { 2181 try { 2182 mLocationManager.removeUpdates(mLocationListeners[i]); 2183 } catch (Exception ex) { 2184 Log.i(TAG, "fail to remove location listners, ignore", ex); 2185 } 2186 } 2187 Log.d(TAG, "stopReceivingLocationUpdates"); 2188 } 2189 hideGpsOnScreenIndicator(); 2190 } 2191 2192 private Location getCurrentLocation() { 2193 // go in best to worst order 2194 for (int i = 0; i < mLocationListeners.length; i++) { 2195 Location l = mLocationListeners[i].current(); 2196 if (l != null) return l; 2197 } 2198 Log.d(TAG, "No location received yet."); 2199 return null; 2200 } 2201 2202 private boolean isCameraIdle() { 2203 return mCameraState == IDLE || mCameraState == FOCUS_SUCCESS || mCameraState == FOCUS_FAIL; 2204 } 2205 2206 private boolean isImageCaptureIntent() { 2207 String action = getIntent().getAction(); 2208 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); 2209 } 2210 2211 private void setupCaptureParams() { 2212 Bundle myExtras = getIntent().getExtras(); 2213 if (myExtras != null) { 2214 mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 2215 mCropValue = myExtras.getString("crop"); 2216 } 2217 } 2218 2219 private void showPostCaptureAlert() { 2220 if (mIsImageCaptureIntent) { 2221 if (mIndicatorWheel == null) { 2222 mShutterButton.setVisibility(View.INVISIBLE); 2223 } else { 2224 mShutterButton.setEnabled(false); 2225 } 2226 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2227 for (int id : pickIds) { 2228 View button = findViewById(id); 2229 ((View) button.getParent()).setVisibility(View.VISIBLE); 2230 } 2231 2232 // Remove the text of the cancel button 2233 View view = findViewById(R.id.btn_cancel); 2234 if (view instanceof Button) ((Button) view).setText(""); 2235 } 2236 } 2237 2238 private void hidePostCaptureAlert() { 2239 if (mIsImageCaptureIntent) { 2240 if (mIndicatorWheel == null) { 2241 mShutterButton.setVisibility(View.VISIBLE); 2242 } else { 2243 mShutterButton.setEnabled(true); 2244 } 2245 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2246 for (int id : pickIds) { 2247 View button = findViewById(id); 2248 ((View) button.getParent()).setVisibility(View.GONE); 2249 } 2250 enableCameraControls(true); 2251 2252 // Restore the text of the cancel button 2253 View view = findViewById(R.id.btn_cancel); 2254 if (view instanceof Button) { 2255 ((Button) view).setText(R.string.review_cancel); 2256 } 2257 } 2258 } 2259 2260 @Override 2261 public boolean onPrepareOptionsMenu(Menu menu) { 2262 super.onPrepareOptionsMenu(menu); 2263 // Only show the menu when camera is idle. 2264 for (int i = 0; i < menu.size(); i++) { 2265 menu.getItem(i).setVisible(isCameraIdle()); 2266 } 2267 2268 return true; 2269 } 2270 2271 @Override 2272 public boolean onCreateOptionsMenu(Menu menu) { 2273 super.onCreateOptionsMenu(menu); 2274 2275 if (mIsImageCaptureIntent) { 2276 // No options menu for attach mode. 2277 return false; 2278 } else { 2279 addBaseMenuItems(menu); 2280 } 2281 return true; 2282 } 2283 2284 private void addBaseMenuItems(Menu menu) { 2285 MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() { 2286 public void run() { 2287 switchToVideoMode(); 2288 } 2289 }); 2290 MenuItem gallery = menu.add(Menu.NONE, Menu.NONE, 2291 MenuHelper.POSITION_GOTO_GALLERY, 2292 R.string.camera_gallery_photos_text) 2293 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2294 public boolean onMenuItemClick(MenuItem item) { 2295 gotoGallery(); 2296 return true; 2297 } 2298 }); 2299 gallery.setIcon(android.R.drawable.ic_menu_gallery); 2300 mGalleryItems.add(gallery); 2301 2302 if (mNumberOfCameras > 1) { 2303 menu.add(Menu.NONE, Menu.NONE, 2304 MenuHelper.POSITION_SWITCH_CAMERA_ID, 2305 R.string.switch_camera_id) 2306 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2307 public boolean onMenuItemClick(MenuItem item) { 2308 CameraSettings.writePreferredCameraId(mPreferences, 2309 ((mCameraId == mFrontCameraId) 2310 ? mBackCameraId : mFrontCameraId)); 2311 onSharedPreferenceChanged(); 2312 return true; 2313 } 2314 }).setIcon(android.R.drawable.ic_menu_camera); 2315 } 2316 } 2317 2318 private boolean switchToVideoMode() { 2319 if (isFinishing() || !isCameraIdle()) return false; 2320 MenuHelper.gotoVideoMode(Camera.this); 2321 mHandler.removeMessages(FIRST_TIME_INIT); 2322 finish(); 2323 return true; 2324 } 2325 2326 public boolean onSwitchChanged(Switcher source, boolean onOff) { 2327 if (onOff == SWITCH_VIDEO) { 2328 return switchToVideoMode(); 2329 } else { 2330 return true; 2331 } 2332 } 2333 2334 private void onSharedPreferenceChanged() { 2335 // ignore the events after "onPause()" 2336 if (mPausing) return; 2337 2338 boolean recordLocation; 2339 2340 recordLocation = RecordLocationPreference.get( 2341 mPreferences, getContentResolver()); 2342 2343 if (mRecordLocation != recordLocation) { 2344 mRecordLocation = recordLocation; 2345 if (mRecordLocation) { 2346 startReceivingLocationUpdates(); 2347 } else { 2348 stopReceivingLocationUpdates(); 2349 } 2350 } 2351 int cameraId = CameraSettings.readPreferredCameraId(mPreferences); 2352 if (mCameraId != cameraId) { 2353 // Restart the activity to have a crossfade animation. 2354 // TODO: Use SurfaceTexture to implement a better and faster 2355 // animation. 2356 if (mIsImageCaptureIntent) { 2357 // If the intent is camera capture, stay in camera capture mode. 2358 MenuHelper.gotoCameraMode(this, getIntent()); 2359 } else { 2360 MenuHelper.gotoCameraMode(this); 2361 } 2362 2363 finish(); 2364 } else { 2365 setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE); 2366 } 2367 } 2368 2369 @Override 2370 public void onUserInteraction() { 2371 super.onUserInteraction(); 2372 keepScreenOnAwhile(); 2373 } 2374 2375 private void resetScreenOn() { 2376 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2377 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2378 } 2379 2380 private void keepScreenOnAwhile() { 2381 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2382 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2383 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 2384 } 2385 2386 private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener { 2387 2388 public void onSharedPreferenceChanged() { 2389 Camera.this.onSharedPreferenceChanged(); 2390 } 2391 2392 public void onRestorePreferencesClicked() { 2393 Camera.this.onRestorePreferencesClicked(); 2394 } 2395 2396 public void onPopupWindowVisibilityChanged(int visibility) { 2397 } 2398 } 2399 2400 protected void onRestorePreferencesClicked() { 2401 if (mPausing) return; 2402 Runnable runnable = new Runnable() { 2403 public void run() { 2404 restorePreferences(); 2405 } 2406 }; 2407 MenuHelper.confirmAction(this, 2408 getString(R.string.confirm_restore_title), 2409 getString(R.string.confirm_restore_message), 2410 runnable); 2411 } 2412 2413 private void restorePreferences() { 2414 // Reset the zoom. Zoom value is not stored in preference. 2415 if (mParameters.isZoomSupported()) { 2416 mZoomValue = 0; 2417 setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM); 2418 if (mZoomPicker != null) mZoomPicker.setZoomIndex(0); 2419 } 2420 2421 if (mHeadUpDisplay != null) { 2422 mHeadUpDisplay.restorePreferences(mParameters); 2423 } 2424 2425 if (mIndicatorWheel != null) { 2426 mIndicatorWheel.dismissSettingPopup(); 2427 CameraSettings.restorePreferences(Camera.this, mPreferences, 2428 mParameters); 2429 initializeIndicatorWheel(); 2430 onSharedPreferenceChanged(); 2431 } 2432 } 2433 2434 protected void onOverriddenPreferencesClicked() { 2435 if (mPausing) return; 2436 if (mNotSelectableToast == null) { 2437 String str = getResources().getString(R.string.not_selectable_in_scene_mode); 2438 mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT); 2439 } 2440 mNotSelectableToast.show(); 2441 } 2442 2443 private void showSharePopup() { 2444 Uri uri = mThumbnail.getUri(); 2445 if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) { 2446 mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(), "image/jpeg", 2447 mOrientationCompensation, mShareButton); 2448 } 2449 mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0); 2450 } 2451 2452 private class MyIndicatorWheelListener implements IndicatorWheel.Listener { 2453 public void onSharedPreferenceChanged() { 2454 Camera.this.onSharedPreferenceChanged(); 2455 } 2456 2457 public void onRestorePreferencesClicked() { 2458 Camera.this.onRestorePreferencesClicked(); 2459 } 2460 2461 public void onOverriddenPreferencesClicked() { 2462 Camera.this.onOverriddenPreferencesClicked(); 2463 } 2464 } 2465 2466 private class MyCameraPickerListener implements CameraPicker.Listener { 2467 public void onSharedPreferenceChanged() { 2468 Camera.this.onSharedPreferenceChanged(); 2469 } 2470 } 2471} 2472