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