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