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