Camera.java revision 3d108b88030763f102398487e9b9e74fb67b47a8
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 if (e.getAction() != MotionEvent.ACTION_DOWN) return false; 1584 1585 // Do not trigger touch focus when popup window is dismissed. 1586 if (collapseCameraControls()) return false; 1587 1588 if (mPausing || !mFirstTimeInitialized || !canTakePicture()) { 1589 return false; 1590 } 1591 1592 // Take a picture if metering area or focus area is supported. 1593 if (mParameters.getMaxNumMeteringAreas() == 0 1594 && (mParameters.getMaxNumFocusAreas() == 0 1595 || (!mFocusMode.equals(Parameters.FOCUS_MODE_AUTO) && 1596 !mFocusMode.equals(Parameters.FOCUS_MODE_MACRO) && 1597 !mFocusMode.equals(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)))) { 1598 return false; 1599 } 1600 1601 // Calculate the position of the focus rectangle. 1602 int x = Math.round(e.getX()); 1603 int y = Math.round(e.getY()); 1604 int focusWidth = mFocusRectangle.getWidth(); 1605 int focusHeight = mFocusRectangle.getHeight(); 1606 int left = Util.clamp(x - focusWidth / 2, 0, 1607 mPreviewFrame.getWidth() - focusWidth); 1608 int top = Util.clamp(y - focusHeight / 2, 0, 1609 mPreviewFrame.getHeight() - focusHeight); 1610 Log.d(TAG, "x=" + x + ". y=" + y); 1611 Log.d(TAG, "Margin left=" + left + " . Margin top=" + top); 1612 Log.d(TAG, "mPreviewFrame width=" + mPreviewFrame.getWidth() + 1613 "mPreviewFrame.getHeight()="+mPreviewFrame.getHeight()); 1614 1615 // Convert the coordinates to driver format. The coordinates range from 1616 // -1000 to 1000. 1617 if (mFocusArea == null) { 1618 mFocusArea = new ArrayList<Area>(); 1619 mFocusArea.add(new Area(new Rect(), 1)); 1620 } 1621 Rect rect = mFocusArea.get(0).rect; 1622 rect.left = (int) ((double) left / mPreviewFrame.getWidth() * 2000 - 1000); 1623 rect.top = (int) ((double) top / mPreviewFrame.getHeight() * 2000 - 1000); 1624 rect.right = (int) ((double) (left + focusWidth) 1625 / mPreviewFrame.getWidth() * 2000 - 1000); 1626 rect.bottom = (int) ((double) (top + focusHeight) 1627 / mPreviewFrame.getHeight() * 2000 - 1000); 1628 1629 // Use margin to set the focus rectangle to the touched area. 1630 RelativeLayout.LayoutParams p = 1631 (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams(); 1632 p.setMargins(left + mPreviewBorder.getPaddingLeft(), 1633 top + mPreviewBorder.getPaddingTop(), 0, 0); 1634 // Disable "center" rule because we no longer want to put it in the center. 1635 int[] rules = p.getRules(); 1636 rules[RelativeLayout.CENTER_IN_PARENT] = 0; 1637 mFocusRectangle.requestLayout(); 1638 1639 // Set the focus area and do autofocus. 1640 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1641 autoFocus(); 1642 1643 return true; 1644 } 1645 1646 void resetTouchFocus() { 1647 // Put focus rectangle to the center. 1648 RelativeLayout.LayoutParams p = 1649 (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams(); 1650 int[] rules = p.getRules(); 1651 rules[RelativeLayout.CENTER_IN_PARENT] = RelativeLayout.TRUE; 1652 p.setMargins(0, 0, 0, 0); 1653 1654 mFocusArea = null; 1655 } 1656 1657 @Override 1658 public void onBackPressed() { 1659 if (!isCameraIdle()) { 1660 // ignore backs while we're taking a picture 1661 return; 1662 } else if (!collapseCameraControls()) { 1663 super.onBackPressed(); 1664 } 1665 } 1666 1667 @Override 1668 public boolean onKeyDown(int keyCode, KeyEvent event) { 1669 switch (keyCode) { 1670 case KeyEvent.KEYCODE_FOCUS: 1671 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1672 doFocus(true); 1673 } 1674 return true; 1675 case KeyEvent.KEYCODE_CAMERA: 1676 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1677 doSnap(); 1678 } 1679 return true; 1680 case KeyEvent.KEYCODE_DPAD_CENTER: 1681 // If we get a dpad center event without any focused view, move 1682 // the focus to the shutter button and press it. 1683 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1684 // Start auto-focus immediately to reduce shutter lag. After 1685 // the shutter button gets the focus, doFocus() will be 1686 // called again but it is fine. 1687 if (collapseCameraControls()) return true; 1688 doFocus(true); 1689 if (mShutterButton.isInTouchMode()) { 1690 mShutterButton.requestFocusFromTouch(); 1691 } else { 1692 mShutterButton.requestFocus(); 1693 } 1694 mShutterButton.setPressed(true); 1695 } 1696 return true; 1697 } 1698 1699 return super.onKeyDown(keyCode, event); 1700 } 1701 1702 @Override 1703 public boolean onKeyUp(int keyCode, KeyEvent event) { 1704 switch (keyCode) { 1705 case KeyEvent.KEYCODE_FOCUS: 1706 if (mFirstTimeInitialized) { 1707 doFocus(false); 1708 } 1709 return true; 1710 } 1711 return super.onKeyUp(keyCode, event); 1712 } 1713 1714 private void doSnap() { 1715 if (collapseCameraControls()) return; 1716 1717 Log.v(TAG, "doSnap: mCameraState=" + mCameraState); 1718 // If the user has half-pressed the shutter and focus is completed, we 1719 // can take the photo right away. If the focus mode is infinity, we can 1720 // also take the photo. 1721 if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY) 1722 || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED) 1723 || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF) 1724 || (mCameraState == FOCUS_SUCCESS 1725 || mCameraState == FOCUS_FAIL)) { 1726 capture(); 1727 } else if (mCameraState == FOCUSING) { 1728 // Half pressing the shutter (i.e. the focus button event) will 1729 // already have requested AF for us, so just request capture on 1730 // focus here. 1731 mCameraState = FOCUSING_SNAP_ON_FINISH; 1732 } else if (mCameraState == IDLE) { 1733 // Focus key down event is dropped for some reasons. Just ignore. 1734 } 1735 } 1736 1737 private void doFocus(boolean pressed) { 1738 // Do the focus if the mode is not infinity. 1739 if (collapseCameraControls()) return; 1740 if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY) 1741 || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED) 1742 || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) { 1743 if (pressed) { // Focus key down. 1744 // Do not do focus if there is not enoguh storage. Do not focus 1745 // if touch focus has been triggered, that is, camera state is 1746 // FOCUS_SUCCESS or FOCUS_FAIL. 1747 if (canTakePicture() && mCameraState != FOCUS_SUCCESS 1748 && mCameraState != FOCUS_FAIL) { 1749 autoFocus(); 1750 } 1751 } else { // Focus key up. 1752 // User releases half-pressed focus key. 1753 if (mCameraState == FOCUSING || mCameraState == FOCUS_SUCCESS 1754 || mCameraState == FOCUS_FAIL) { 1755 cancelAutoFocus(); 1756 } 1757 } 1758 } 1759 } 1760 1761 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1762 // Make sure we have a surface in the holder before proceeding. 1763 if (holder.getSurface() == null) { 1764 Log.d(TAG, "holder.getSurface() == null"); 1765 return; 1766 } 1767 1768 Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h); 1769 1770 // We need to save the holder for later use, even when the mCameraDevice 1771 // is null. This could happen if onResume() is invoked after this 1772 // function. 1773 mSurfaceHolder = holder; 1774 1775 // The mCameraDevice will be null if it fails to connect to the camera 1776 // hardware. In this case we will show a dialog and then finish the 1777 // activity, so it's OK to ignore it. 1778 if (mCameraDevice == null) return; 1779 1780 // Sometimes surfaceChanged is called after onPause or before onResume. 1781 // Ignore it. 1782 if (mPausing || isFinishing()) return; 1783 1784 // Set preview display if the surface is being created. Preview was 1785 // already started. Also restart the preview if display rotation has 1786 // changed. Sometimes this happens when the device is held in portrait 1787 // and camera app is opened. Rotation animation takes some time and 1788 // display rotation in onCreate may not be what we want. 1789 if (mCameraState != PREVIEW_STOPPED 1790 && (Util.getDisplayRotation(this) == mDisplayRotation) 1791 && holder.isCreating()) { 1792 // Set preview display if the surface is being created and preview 1793 // was already started. That means preview display was set to null 1794 // and we need to set it now. 1795 setPreviewDisplay(holder); 1796 } else { 1797 // 1. Restart the preview if the size of surface was changed. The 1798 // framework may not support changing preview display on the fly. 1799 // 2. Start the preview now if surface was destroyed and preview 1800 // stopped. 1801 restartPreview(); 1802 } 1803 1804 // If first time initialization is not finished, send a message to do 1805 // it later. We want to finish surfaceChanged as soon as possible to let 1806 // user see preview first. 1807 if (!mFirstTimeInitialized) { 1808 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1809 } else { 1810 initializeSecondTime(); 1811 } 1812 } 1813 1814 public void surfaceCreated(SurfaceHolder holder) { 1815 } 1816 1817 public void surfaceDestroyed(SurfaceHolder holder) { 1818 stopPreview(); 1819 mSurfaceHolder = null; 1820 } 1821 1822 private void closeCamera() { 1823 if (mCameraDevice != null) { 1824 CameraHolder.instance().release(); 1825 mCameraDevice.setZoomChangeListener(null); 1826 mCameraDevice = null; 1827 mCameraState = PREVIEW_STOPPED; 1828 } 1829 } 1830 1831 private void ensureCameraDevice() throws CameraHardwareException { 1832 if (mCameraDevice == null) { 1833 mCameraDevice = CameraHolder.instance().open(mCameraId); 1834 mInitialParams = mCameraDevice.getParameters(); 1835 } 1836 } 1837 1838 private void showCameraErrorAndFinish() { 1839 Resources ress = getResources(); 1840 Util.showFatalErrorAndFinish(Camera.this, 1841 ress.getString(R.string.camera_error_title), 1842 ress.getString(R.string.cannot_connect_camera)); 1843 } 1844 1845 private boolean restartPreview() { 1846 try { 1847 startPreview(); 1848 } catch (CameraHardwareException e) { 1849 showCameraErrorAndFinish(); 1850 return false; 1851 } 1852 return true; 1853 } 1854 1855 private void setPreviewDisplay(SurfaceHolder holder) { 1856 try { 1857 mCameraDevice.setPreviewDisplay(holder); 1858 } catch (Throwable ex) { 1859 closeCamera(); 1860 throw new RuntimeException("setPreviewDisplay failed", ex); 1861 } 1862 } 1863 1864 private void startPreview() throws CameraHardwareException { 1865 if (mPausing || isFinishing()) return; 1866 1867 resetTouchFocus(); 1868 1869 ensureCameraDevice(); 1870 mCameraDevice.setErrorCallback(mErrorCallback); 1871 1872 // If we're previewing already, stop the preview first (this will blank 1873 // the screen). 1874 if (mCameraState != PREVIEW_STOPPED) stopPreview(); 1875 1876 setPreviewDisplay(mSurfaceHolder); 1877 mDisplayRotation = Util.getDisplayRotation(this); 1878 Util.setCameraDisplayOrientation(mDisplayRotation, mCameraId, mCameraDevice); 1879 setCameraParameters(UPDATE_PARAM_ALL); 1880 1881 1882 try { 1883 Log.v(TAG, "startPreview"); 1884 mCameraDevice.startPreview(); 1885 } catch (Throwable ex) { 1886 closeCamera(); 1887 throw new RuntimeException("startPreview failed", ex); 1888 } 1889 mZoomState = ZOOM_STOPPED; 1890 mCameraState = IDLE; 1891 } 1892 1893 private void stopPreview() { 1894 if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { 1895 Log.v(TAG, "stopPreview"); 1896 mCameraDevice.stopPreview(); 1897 } 1898 mCameraState = PREVIEW_STOPPED; 1899 // If auto focus was in progress, it would have been canceled. 1900 updateFocusUI(); 1901 } 1902 1903 private static boolean isSupported(String value, List<String> supported) { 1904 return supported == null ? false : supported.indexOf(value) >= 0; 1905 } 1906 1907 private void updateCameraParametersInitialize() { 1908 // Reset preview frame rate to the maximum because it may be lowered by 1909 // video camera application. 1910 List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); 1911 if (frameRates != null) { 1912 Integer max = Collections.max(frameRates); 1913 mParameters.setPreviewFrameRate(max); 1914 } 1915 1916 } 1917 1918 private void updateCameraParametersZoom() { 1919 // Set zoom. 1920 if (mParameters.isZoomSupported()) { 1921 mParameters.setZoom(mZoomValue); 1922 } 1923 } 1924 1925 private void updateCameraParametersPreference() { 1926 if (mParameters.getMaxNumFocusAreas() > 0) { 1927 mParameters.setFocusAreas(mFocusArea); 1928 Log.d(TAG, "Parameter focus areas=" + mParameters.get("focus-areas")); 1929 } 1930 1931 if (mParameters.getMaxNumMeteringAreas() > 0) { 1932 // Use the same area for focus and metering. 1933 mParameters.setMeteringAreas(mFocusArea); 1934 } 1935 1936 // Set picture size. 1937 String pictureSize = mPreferences.getString( 1938 CameraSettings.KEY_PICTURE_SIZE, null); 1939 if (pictureSize == null) { 1940 CameraSettings.initialCameraPictureSize(this, mParameters); 1941 } else { 1942 List<Size> supported = mParameters.getSupportedPictureSizes(); 1943 CameraSettings.setCameraPictureSize( 1944 pictureSize, supported, mParameters); 1945 } 1946 1947 // Set the preview frame aspect ratio according to the picture size. 1948 Size size = mParameters.getPictureSize(); 1949 PreviewFrameLayout frameLayout = 1950 (PreviewFrameLayout) findViewById(R.id.frame_layout); 1951 frameLayout.setAspectRatio((double) size.width / size.height); 1952 1953 // Set a preview size that is closest to the viewfinder height and has 1954 // the right aspect ratio. 1955 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 1956 Size optimalSize = Util.getOptimalPreviewSize(this, 1957 sizes, (double) size.width / size.height); 1958 Size original = mParameters.getPreviewSize(); 1959 if (!original.equals(optimalSize)) { 1960 mParameters.setPreviewSize(optimalSize.width, optimalSize.height); 1961 1962 // Zoom related settings will be changed for different preview 1963 // sizes, so set and read the parameters to get lastest values 1964 mCameraDevice.setParameters(mParameters); 1965 mParameters = mCameraDevice.getParameters(); 1966 } 1967 Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); 1968 1969 // Since change scene mode may change supported values, 1970 // Set scene mode first, 1971 mSceneMode = mPreferences.getString( 1972 CameraSettings.KEY_SCENE_MODE, 1973 getString(R.string.pref_camera_scenemode_default)); 1974 if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { 1975 if (!mParameters.getSceneMode().equals(mSceneMode)) { 1976 mParameters.setSceneMode(mSceneMode); 1977 mCameraDevice.setParameters(mParameters); 1978 1979 // Setting scene mode will change the settings of flash mode, 1980 // white balance, and focus mode. Here we read back the 1981 // parameters, so we can know those settings. 1982 mParameters = mCameraDevice.getParameters(); 1983 } 1984 } else { 1985 mSceneMode = mParameters.getSceneMode(); 1986 if (mSceneMode == null) { 1987 mSceneMode = Parameters.SCENE_MODE_AUTO; 1988 } 1989 } 1990 1991 // Set JPEG quality. 1992 String jpegQuality = mPreferences.getString( 1993 CameraSettings.KEY_JPEG_QUALITY, 1994 getString(R.string.pref_camera_jpegquality_default)); 1995 mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality)); 1996 1997 // For the following settings, we need to check if the settings are 1998 // still supported by latest driver, if not, ignore the settings. 1999 2000 // Set color effect parameter. 2001 String colorEffect = mPreferences.getString( 2002 CameraSettings.KEY_COLOR_EFFECT, 2003 getString(R.string.pref_camera_coloreffect_default)); 2004 if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) { 2005 mParameters.setColorEffect(colorEffect); 2006 } 2007 2008 // Set exposure compensation 2009 String exposure = mPreferences.getString( 2010 CameraSettings.KEY_EXPOSURE, 2011 getString(R.string.pref_exposure_default)); 2012 try { 2013 int value = Integer.parseInt(exposure); 2014 int max = mParameters.getMaxExposureCompensation(); 2015 int min = mParameters.getMinExposureCompensation(); 2016 if (value >= min && value <= max) { 2017 mParameters.setExposureCompensation(value); 2018 } else { 2019 Log.w(TAG, "invalid exposure range: " + exposure); 2020 } 2021 } catch (NumberFormatException e) { 2022 Log.w(TAG, "invalid exposure: " + exposure); 2023 } 2024 2025 if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 2026 // Set flash mode. 2027 String flashMode = mPreferences.getString( 2028 CameraSettings.KEY_FLASH_MODE, 2029 getString(R.string.pref_camera_flashmode_default)); 2030 List<String> supportedFlash = mParameters.getSupportedFlashModes(); 2031 if (isSupported(flashMode, supportedFlash)) { 2032 mParameters.setFlashMode(flashMode); 2033 } else { 2034 flashMode = mParameters.getFlashMode(); 2035 if (flashMode == null) { 2036 flashMode = getString( 2037 R.string.pref_camera_flashmode_no_flash); 2038 } 2039 } 2040 2041 // Set white balance parameter. 2042 String whiteBalance = mPreferences.getString( 2043 CameraSettings.KEY_WHITE_BALANCE, 2044 getString(R.string.pref_camera_whitebalance_default)); 2045 if (isSupported(whiteBalance, 2046 mParameters.getSupportedWhiteBalance())) { 2047 mParameters.setWhiteBalance(whiteBalance); 2048 } else { 2049 whiteBalance = mParameters.getWhiteBalance(); 2050 if (whiteBalance == null) { 2051 whiteBalance = Parameters.WHITE_BALANCE_AUTO; 2052 } 2053 } 2054 2055 // Set focus mode. 2056 mFocusMode = mPreferences.getString( 2057 CameraSettings.KEY_FOCUS_MODE, 2058 getString(R.string.pref_camera_focusmode_default)); 2059 if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) { 2060 mParameters.setFocusMode(mFocusMode); 2061 } else { 2062 mFocusMode = mParameters.getFocusMode(); 2063 if (mFocusMode == null) { 2064 mFocusMode = Parameters.FOCUS_MODE_AUTO; 2065 } 2066 } 2067 } else { 2068 mFocusMode = mParameters.getFocusMode(); 2069 } 2070 } 2071 2072 // We separate the parameters into several subsets, so we can update only 2073 // the subsets actually need updating. The PREFERENCE set needs extra 2074 // locking because the preference can be changed from GLThread as well. 2075 private void setCameraParameters(int updateSet) { 2076 mParameters = mCameraDevice.getParameters(); 2077 2078 if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) { 2079 updateCameraParametersInitialize(); 2080 } 2081 2082 if ((updateSet & UPDATE_PARAM_ZOOM) != 0) { 2083 updateCameraParametersZoom(); 2084 } 2085 2086 if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) { 2087 updateCameraParametersPreference(); 2088 } 2089 2090 mCameraDevice.setParameters(mParameters); 2091 } 2092 2093 // If the Camera is idle, update the parameters immediately, otherwise 2094 // accumulate them in mUpdateSet and update later. 2095 private void setCameraParametersWhenIdle(int additionalUpdateSet) { 2096 mUpdateSet |= additionalUpdateSet; 2097 if (mCameraDevice == null) { 2098 // We will update all the parameters when we open the device, so 2099 // we don't need to do anything now. 2100 mUpdateSet = 0; 2101 return; 2102 } else if (isCameraIdle()) { 2103 setCameraParameters(mUpdateSet); 2104 updateSceneModeUI(); 2105 mUpdateSet = 0; 2106 } else { 2107 if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) { 2108 mHandler.sendEmptyMessageDelayed( 2109 SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000); 2110 } 2111 } 2112 } 2113 2114 private void gotoGallery() { 2115 MenuHelper.gotoCameraImageGallery(this); 2116 } 2117 2118 private void viewImage(RotateImageView view) { 2119 if(!view.isUriValid()) { 2120 Log.e(TAG, "Uri invalid. uri=" + view.getUri()); 2121 return; 2122 } 2123 2124 try { 2125 startActivity(new Intent( 2126 Util.REVIEW_ACTION, view.getUri())); 2127 } catch (ActivityNotFoundException ex) { 2128 try { 2129 startActivity(new Intent( 2130 Intent.ACTION_VIEW, view.getUri())); 2131 } catch (ActivityNotFoundException e) { 2132 Log.e(TAG, "review image fail. uri=" + view.getUri(), e); 2133 } 2134 } 2135 } 2136 2137 private void startReceivingLocationUpdates() { 2138 if (mLocationManager != null) { 2139 try { 2140 mLocationManager.requestLocationUpdates( 2141 LocationManager.NETWORK_PROVIDER, 2142 1000, 2143 0F, 2144 mLocationListeners[1]); 2145 } catch (SecurityException ex) { 2146 Log.i(TAG, "fail to request location update, ignore", ex); 2147 } catch (IllegalArgumentException ex) { 2148 Log.d(TAG, "provider does not exist " + ex.getMessage()); 2149 } 2150 try { 2151 mLocationManager.requestLocationUpdates( 2152 LocationManager.GPS_PROVIDER, 2153 1000, 2154 0F, 2155 mLocationListeners[0]); 2156 showGpsOnScreenIndicator(false); 2157 } catch (SecurityException ex) { 2158 Log.i(TAG, "fail to request location update, ignore", ex); 2159 } catch (IllegalArgumentException ex) { 2160 Log.d(TAG, "provider does not exist " + ex.getMessage()); 2161 } 2162 Log.d(TAG, "startReceivingLocationUpdates"); 2163 } 2164 } 2165 2166 private void stopReceivingLocationUpdates() { 2167 if (mLocationManager != null) { 2168 for (int i = 0; i < mLocationListeners.length; i++) { 2169 try { 2170 mLocationManager.removeUpdates(mLocationListeners[i]); 2171 } catch (Exception ex) { 2172 Log.i(TAG, "fail to remove location listners, ignore", ex); 2173 } 2174 } 2175 Log.d(TAG, "stopReceivingLocationUpdates"); 2176 } 2177 hideGpsOnScreenIndicator(); 2178 } 2179 2180 private Location getCurrentLocation() { 2181 // go in best to worst order 2182 for (int i = 0; i < mLocationListeners.length; i++) { 2183 Location l = mLocationListeners[i].current(); 2184 if (l != null) return l; 2185 } 2186 Log.d(TAG, "No location received yet."); 2187 return null; 2188 } 2189 2190 private boolean isCameraIdle() { 2191 return mCameraState == IDLE || mCameraState == FOCUS_SUCCESS || mCameraState == FOCUS_FAIL; 2192 } 2193 2194 private boolean isImageCaptureIntent() { 2195 String action = getIntent().getAction(); 2196 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); 2197 } 2198 2199 private void setupCaptureParams() { 2200 Bundle myExtras = getIntent().getExtras(); 2201 if (myExtras != null) { 2202 mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 2203 mCropValue = myExtras.getString("crop"); 2204 } 2205 } 2206 2207 private void showPostCaptureAlert() { 2208 if (mIsImageCaptureIntent) { 2209 if (mIndicatorWheel == null) { 2210 mShutterButton.setVisibility(View.INVISIBLE); 2211 } else { 2212 mShutterButton.setEnabled(false); 2213 } 2214 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2215 for (int id : pickIds) { 2216 View button = findViewById(id); 2217 ((View) button.getParent()).setVisibility(View.VISIBLE); 2218 } 2219 2220 // Remove the text of the cancel button 2221 View view = findViewById(R.id.btn_cancel); 2222 if (view instanceof Button) ((Button) view).setText(""); 2223 } 2224 } 2225 2226 private void hidePostCaptureAlert() { 2227 if (mIsImageCaptureIntent) { 2228 if (mIndicatorWheel == null) { 2229 mShutterButton.setVisibility(View.VISIBLE); 2230 } else { 2231 mShutterButton.setEnabled(true); 2232 } 2233 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2234 for (int id : pickIds) { 2235 View button = findViewById(id); 2236 ((View) button.getParent()).setVisibility(View.GONE); 2237 } 2238 enableCameraControls(true); 2239 2240 // Restore the text of the cancel button 2241 View view = findViewById(R.id.btn_cancel); 2242 if (view instanceof Button) { 2243 ((Button) view).setText(R.string.review_cancel); 2244 } 2245 } 2246 } 2247 2248 @Override 2249 public boolean onPrepareOptionsMenu(Menu menu) { 2250 super.onPrepareOptionsMenu(menu); 2251 // Only show the menu when camera is idle. 2252 for (int i = 0; i < menu.size(); i++) { 2253 menu.getItem(i).setVisible(isCameraIdle()); 2254 } 2255 2256 return true; 2257 } 2258 2259 @Override 2260 public boolean onCreateOptionsMenu(Menu menu) { 2261 super.onCreateOptionsMenu(menu); 2262 2263 if (mIsImageCaptureIntent) { 2264 // No options menu for attach mode. 2265 return false; 2266 } else { 2267 addBaseMenuItems(menu); 2268 } 2269 return true; 2270 } 2271 2272 private void addBaseMenuItems(Menu menu) { 2273 MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() { 2274 public void run() { 2275 switchToVideoMode(); 2276 } 2277 }); 2278 MenuItem gallery = menu.add(Menu.NONE, Menu.NONE, 2279 MenuHelper.POSITION_GOTO_GALLERY, 2280 R.string.camera_gallery_photos_text) 2281 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2282 public boolean onMenuItemClick(MenuItem item) { 2283 gotoGallery(); 2284 return true; 2285 } 2286 }); 2287 gallery.setIcon(android.R.drawable.ic_menu_gallery); 2288 mGalleryItems.add(gallery); 2289 2290 if (mNumberOfCameras > 1) { 2291 menu.add(Menu.NONE, Menu.NONE, 2292 MenuHelper.POSITION_SWITCH_CAMERA_ID, 2293 R.string.switch_camera_id) 2294 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2295 public boolean onMenuItemClick(MenuItem item) { 2296 CameraSettings.writePreferredCameraId(mPreferences, 2297 ((mCameraId == mFrontCameraId) 2298 ? mBackCameraId : mFrontCameraId)); 2299 onSharedPreferenceChanged(); 2300 return true; 2301 } 2302 }).setIcon(android.R.drawable.ic_menu_camera); 2303 } 2304 } 2305 2306 private boolean switchToVideoMode() { 2307 if (isFinishing() || !isCameraIdle()) return false; 2308 MenuHelper.gotoVideoMode(Camera.this); 2309 mHandler.removeMessages(FIRST_TIME_INIT); 2310 finish(); 2311 return true; 2312 } 2313 2314 public boolean onSwitchChanged(Switcher source, boolean onOff) { 2315 if (onOff == SWITCH_VIDEO) { 2316 return switchToVideoMode(); 2317 } else { 2318 return true; 2319 } 2320 } 2321 2322 private void onSharedPreferenceChanged() { 2323 // ignore the events after "onPause()" 2324 if (mPausing) return; 2325 2326 boolean recordLocation; 2327 2328 recordLocation = RecordLocationPreference.get( 2329 mPreferences, getContentResolver()); 2330 2331 if (mRecordLocation != recordLocation) { 2332 mRecordLocation = recordLocation; 2333 if (mRecordLocation) { 2334 startReceivingLocationUpdates(); 2335 } else { 2336 stopReceivingLocationUpdates(); 2337 } 2338 } 2339 int cameraId = CameraSettings.readPreferredCameraId(mPreferences); 2340 if (mCameraId != cameraId) { 2341 // Restart the activity to have a crossfade animation. 2342 // TODO: Use SurfaceTexture to implement a better and faster 2343 // animation. 2344 if (mIsImageCaptureIntent) { 2345 // If the intent is camera capture, stay in camera capture mode. 2346 MenuHelper.gotoCameraMode(this, getIntent()); 2347 } else { 2348 MenuHelper.gotoCameraMode(this); 2349 } 2350 2351 finish(); 2352 } else { 2353 setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE); 2354 } 2355 } 2356 2357 @Override 2358 public void onUserInteraction() { 2359 super.onUserInteraction(); 2360 keepScreenOnAwhile(); 2361 } 2362 2363 private void resetScreenOn() { 2364 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2365 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2366 } 2367 2368 private void keepScreenOnAwhile() { 2369 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2370 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2371 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 2372 } 2373 2374 private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener { 2375 2376 public void onSharedPreferenceChanged() { 2377 Camera.this.onSharedPreferenceChanged(); 2378 } 2379 2380 public void onRestorePreferencesClicked() { 2381 Camera.this.onRestorePreferencesClicked(); 2382 } 2383 2384 public void onPopupWindowVisibilityChanged(int visibility) { 2385 } 2386 } 2387 2388 protected void onRestorePreferencesClicked() { 2389 if (mPausing) return; 2390 Runnable runnable = new Runnable() { 2391 public void run() { 2392 restorePreferences(); 2393 } 2394 }; 2395 MenuHelper.confirmAction(this, 2396 getString(R.string.confirm_restore_title), 2397 getString(R.string.confirm_restore_message), 2398 runnable); 2399 } 2400 2401 private void restorePreferences() { 2402 // Reset the zoom. Zoom value is not stored in preference. 2403 if (mParameters.isZoomSupported()) { 2404 mZoomValue = 0; 2405 setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM); 2406 if (mZoomPicker != null) mZoomPicker.setZoomIndex(0); 2407 } 2408 2409 if (mHeadUpDisplay != null) { 2410 mHeadUpDisplay.restorePreferences(mParameters); 2411 } 2412 2413 if (mIndicatorWheel != null) { 2414 mIndicatorWheel.dismissSettingPopup(); 2415 CameraSettings.restorePreferences(Camera.this, mPreferences, 2416 mParameters); 2417 initializeIndicatorWheel(); 2418 onSharedPreferenceChanged(); 2419 } 2420 } 2421 2422 protected void onOverriddenPreferencesClicked() { 2423 if (mPausing) return; 2424 if (mNotSelectableToast == null) { 2425 String str = getResources().getString(R.string.not_selectable_in_scene_mode); 2426 mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT); 2427 } 2428 mNotSelectableToast.cancel(); 2429 mNotSelectableToast.show(); 2430 } 2431 2432 private class MyIndicatorWheelListener implements IndicatorWheel.Listener { 2433 public void onSharedPreferenceChanged() { 2434 Camera.this.onSharedPreferenceChanged(); 2435 } 2436 2437 public void onRestorePreferencesClicked() { 2438 Camera.this.onRestorePreferencesClicked(); 2439 } 2440 2441 public void onOverriddenPreferencesClicked() { 2442 Camera.this.onOverriddenPreferencesClicked(); 2443 } 2444 } 2445 2446 private class MyCameraPickerListener implements CameraPicker.Listener { 2447 public void onSharedPreferenceChanged() { 2448 Camera.this.onSharedPreferenceChanged(); 2449 } 2450 } 2451} 2452