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