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