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