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