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