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