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