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