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