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