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