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