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