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