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