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