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