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