Camera.java revision 42be7712a3f114a7cba8f9e8adf33307509e3fc5
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 clearFocusState() { 1266 mFocusState = FOCUS_NOT_STARTED; 1267 updateFocusIndicator(); 1268 } 1269 1270 private void updateFocusIndicator() { 1271 if (mFocusRectangle == null) return; 1272 1273 if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) { 1274 mFocusRectangle.showStart(); 1275 } else if (mFocusState == FOCUS_SUCCESS) { 1276 mFocusRectangle.showSuccess(); 1277 } else if (mFocusState == FOCUS_FAIL) { 1278 mFocusRectangle.showFail(); 1279 } else { 1280 mFocusRectangle.clear(); 1281 } 1282 } 1283 1284 @Override 1285 public boolean onKeyDown(int keyCode, KeyEvent event) { 1286 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 1287 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1288 1289 switch (keyCode) { 1290 case KeyEvent.KEYCODE_BACK: 1291 if (!isCameraIdle()) { 1292 // ignore backs while we're taking a picture 1293 return true; 1294 } 1295 break; 1296 case KeyEvent.KEYCODE_FOCUS: 1297 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1298 doFocus(true); 1299 } 1300 return true; 1301 case KeyEvent.KEYCODE_CAMERA: 1302 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1303 doSnap(); 1304 } 1305 return true; 1306 case KeyEvent.KEYCODE_DPAD_CENTER: 1307 // If we get a dpad center event without any focused view, move 1308 // the focus to the shutter button and press it. 1309 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1310 // Start auto-focus immediately to reduce shutter lag. After 1311 // the shutter button gets the focus, doFocus() will be 1312 // called again but it is fine. 1313 doFocus(true); 1314 if (mShutterButton.isInTouchMode()) { 1315 mShutterButton.requestFocusFromTouch(); 1316 } else { 1317 mShutterButton.requestFocus(); 1318 } 1319 mShutterButton.setPressed(true); 1320 } 1321 return true; 1322 } 1323 1324 return super.onKeyDown(keyCode, event); 1325 } 1326 1327 @Override 1328 public boolean onKeyUp(int keyCode, KeyEvent event) { 1329 switch (keyCode) { 1330 case KeyEvent.KEYCODE_FOCUS: 1331 if (mFirstTimeInitialized) { 1332 doFocus(false); 1333 } 1334 return true; 1335 } 1336 return super.onKeyUp(keyCode, event); 1337 } 1338 1339 private void doSnap() { 1340 // If the user has half-pressed the shutter and focus is completed, we 1341 // can take the photo right away. If the focus mode is infinity, we can 1342 // also take the photo. 1343 if (mFocusMode.equals(getString( 1344 R.string.pref_camera_focusmode_value_infinity)) 1345 || (mFocusState == FOCUS_SUCCESS 1346 || mFocusState == FOCUS_FAIL)) { 1347 if (mZoomButtons != null) mZoomButtons.setVisible(false); 1348 mImageCapture.onSnap(); 1349 } else if (mFocusState == FOCUSING) { 1350 // Half pressing the shutter (i.e. the focus button event) will 1351 // already have requested AF for us, so just request capture on 1352 // focus here. 1353 mFocusState = FOCUSING_SNAP_ON_FINISH; 1354 } else if (mFocusState == FOCUS_NOT_STARTED) { 1355 // Focus key down event is dropped for some reasons. Just ignore. 1356 } 1357 } 1358 1359 private void doFocus(boolean pressed) { 1360 // Do the focus if the mode is auto. No focus needed in infinity mode. 1361 if (mFocusMode.equals(getString( 1362 R.string.pref_camera_focusmode_value_auto))) { 1363 if (pressed) { // Focus key down. 1364 autoFocus(); 1365 } else { // Focus key up. 1366 if (mFocusState != FOCUSING_SNAP_ON_FINISH) { 1367 // User releases half-pressed focus key. 1368 clearFocusState(); 1369 } 1370 } 1371 } 1372 } 1373 1374 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1375 // Make sure we have a surface in the holder before proceeding. 1376 if (holder.getSurface() == null) { 1377 Log.d(TAG, "holder.getSurface() == null"); 1378 return; 1379 } 1380 1381 // The mCameraDevice will be null if it fails to connect to the camera 1382 // hardware. In this case we will show a dialog and then finish the 1383 // activity, so it's OK to ignore it. 1384 if (mCameraDevice == null) return; 1385 1386 mSurfaceHolder = holder; 1387 mViewFinderWidth = w; 1388 mViewFinderHeight = h; 1389 1390 // Sometimes surfaceChanged is called after onPause. Ignore it. 1391 if (mPausing || isFinishing()) return; 1392 1393 // Set preview display if the surface is being created. Preview was 1394 // already started. 1395 if (holder.isCreating()) { 1396 setPreviewDisplay(holder); 1397 } 1398 1399 // If first time initialization is not finished, send a message to do 1400 // it later. We want to finish surfaceChanged as soon as possible to let 1401 // user see preview first. 1402 if (!mFirstTimeInitialized) { 1403 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1404 } else { 1405 initializeSecondTime(); 1406 } 1407 } 1408 1409 public void surfaceCreated(SurfaceHolder holder) { 1410 } 1411 1412 public void surfaceDestroyed(SurfaceHolder holder) { 1413 stopPreview(); 1414 mSurfaceHolder = null; 1415 } 1416 1417 private void closeCamera() { 1418 if (mCameraDevice != null) { 1419 CameraHolder.instance().release(); 1420 mCameraDevice = null; 1421 mPreviewing = false; 1422 } 1423 } 1424 1425 private void ensureCameraDevice() throws CameraHardwareException { 1426 if (mCameraDevice == null) { 1427 mCameraDevice = CameraHolder.instance().open(); 1428 } 1429 } 1430 1431 private void updateLastImage() { 1432 IImageList list = ImageManager.makeImageList( 1433 mContentResolver, 1434 dataLocation(), 1435 ImageManager.INCLUDE_IMAGES, 1436 ImageManager.SORT_ASCENDING, 1437 ImageManager.CAMERA_IMAGE_BUCKET_ID); 1438 int count = list.getCount(); 1439 if (count > 0) { 1440 IImage image = list.getImageAt(count - 1); 1441 Uri uri = image.fullSizeImageUri(); 1442 mThumbController.setData(uri, image.miniThumbBitmap()); 1443 } else { 1444 mThumbController.setData(null, null); 1445 } 1446 list.close(); 1447 } 1448 1449 private void showCameraErrorAndFinish() { 1450 Resources ress = getResources(); 1451 Util.showFatalErrorAndFinish(Camera.this, 1452 ress.getString(R.string.camera_error_title), 1453 ress.getString(R.string.cannot_connect_camera)); 1454 } 1455 1456 private void restartPreview() { 1457 // make sure the surfaceview fills the whole screen when previewing 1458 mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE); 1459 try { 1460 startPreview(); 1461 } catch (CameraHardwareException e) { 1462 showCameraErrorAndFinish(); 1463 return; 1464 } 1465 1466 // Calculate this in advance of each shot so we don't add to shutter 1467 // latency. It's true that someone else could write to the SD card in 1468 // the mean time and fill it, but that could have happened between the 1469 // shutter press and saving the JPEG too. 1470 calculatePicturesRemaining(); 1471 } 1472 1473 private void setPreviewDisplay(SurfaceHolder holder) { 1474 try { 1475 mCameraDevice.setPreviewDisplay(holder); 1476 } catch (Throwable ex) { 1477 closeCamera(); 1478 throw new RuntimeException("setPreviewDisplay failed", ex); 1479 } 1480 } 1481 1482 private void startPreview() throws CameraHardwareException { 1483 if (mPausing || isFinishing()) return; 1484 1485 ensureCameraDevice(); 1486 1487 // If we're previewing already, stop the preview first (this will blank 1488 // the screen). 1489 if (mPreviewing) stopPreview(); 1490 1491 setPreviewDisplay(mSurfaceHolder); 1492 1493 setCameraParameter(); 1494 1495 final long wallTimeStart = SystemClock.elapsedRealtime(); 1496 final long threadTimeStart = Debug.threadCpuTimeNanos(); 1497 1498 // Set one shot preview callback for latency measurement. 1499 mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback); 1500 mCameraDevice.setErrorCallback(mErrorCallback); 1501 1502 try { 1503 Log.v(TAG, "startPreview"); 1504 mCameraDevice.startPreview(); 1505 } catch (Throwable ex) { 1506 closeCamera(); 1507 throw new RuntimeException("startPreview failed", ex); 1508 } 1509 mPreviewing = true; 1510 mStatus = IDLE; 1511 1512 long threadTimeEnd = Debug.threadCpuTimeNanos(); 1513 long wallTimeEnd = SystemClock.elapsedRealtime(); 1514 if ((wallTimeEnd - wallTimeStart) > 3000) { 1515 Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) 1516 + " ms. Thread time was" 1517 + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); 1518 } 1519 } 1520 1521 private void stopPreview() { 1522 if (mCameraDevice != null && mPreviewing) { 1523 Log.v(TAG, "stopPreview"); 1524 mCameraDevice.stopPreview(); 1525 } 1526 mPreviewing = false; 1527 // If auto focus was in progress, it would have been canceled. 1528 clearFocusState(); 1529 } 1530 1531 private void resizeForPreviewAspectRatio(View v) { 1532 ViewGroup.LayoutParams params; 1533 params = v.getLayoutParams(); 1534 Size size = mParameters.getPreviewSize(); 1535 params.width = (int) (params.height * size.width / size.height); 1536 Log.v(TAG, "resize to " + params.width + "x" + params.height); 1537 v.setLayoutParams(params); 1538 } 1539 1540 private Size getOptimalPreviewSize(List<Size> sizes) { 1541 Size optimalSize = null; 1542 if (sizes != null) { 1543 optimalSize = sizes.get(0); 1544 for (int i = 1; i < sizes.size(); i++) { 1545 if (Math.abs(sizes.get(i).height - mViewFinderHeight) < 1546 Math.abs(optimalSize.height - mViewFinderHeight)) { 1547 optimalSize = sizes.get(i); 1548 } 1549 } 1550 Log.v(TAG, "Optimal preview size is " + optimalSize.width + "x" 1551 + optimalSize.height); 1552 } 1553 return optimalSize; 1554 } 1555 1556 private void setCameraParameter() { 1557 mParameters = mCameraDevice.getParameters(); 1558 1559 // Reset preview frame rate to the maximum because it may be lowered by 1560 // video camera application. 1561 List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); 1562 if (frameRates != null) { 1563 Integer max = Collections.max(frameRates); 1564 mParameters.setPreviewFrameRate(max); 1565 } 1566 1567 // Set a preview size that is closest to the viewfinder height. 1568 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 1569 Size optimalSize = getOptimalPreviewSize(sizes); 1570 if (optimalSize != null) { 1571 mParameters.setPreviewSize(optimalSize.width, optimalSize.height); 1572 } 1573 1574 // Set picture size. 1575 String pictureSize = mPreferences.getString( 1576 CameraSettings.KEY_PICTURE_SIZE, 1577 getString(R.string.pref_camera_picturesize_default)); 1578 setCameraPictureSizeIfSupported(pictureSize); 1579 1580 // Set JPEG quality. 1581 String jpegQuality = mPreferences.getString( 1582 CameraSettings.KEY_JPEG_QUALITY, 1583 getString(R.string.pref_camera_jpegquality_default)); 1584 mParameters.setJpegQuality(Integer.parseInt(jpegQuality)); 1585 1586 // Set flash mode. 1587 if (mParameters.getSupportedFlashModes() != null) { 1588 String flashMode = mPreferences.getString( 1589 CameraSettings.KEY_FLASH_MODE, "auto"); 1590 mParameters.setFlashMode(flashMode); 1591 } 1592 1593 // Set white balance parameter. 1594 if (mParameters.getSupportedWhiteBalance() != null) { 1595 String whiteBalance = mPreferences.getString( 1596 CameraSettings.KEY_WHITE_BALANCE, 1597 getString(R.string.pref_camera_whitebalance_default)); 1598 mParameters.setWhiteBalance(whiteBalance); 1599 } 1600 1601 // Set color effect parameter. 1602 if (mParameters.getSupportedColorEffects() != null) { 1603 String colorEffect = mPreferences.getString( 1604 CameraSettings.KEY_COLOR_EFFECT, 1605 getString(R.string.pref_camera_coloreffect_default)); 1606 mParameters.setColorEffect(colorEffect); 1607 } 1608 1609 mCameraDevice.setParameters(mParameters); 1610 } 1611 1612 private void gotoGallery() { 1613 MenuHelper.gotoCameraImageGallery(this); 1614 } 1615 1616 private void viewLastImage() { 1617 if (mThumbController.isUriValid()) { 1618 Uri targetUri = mThumbController.getUri(); 1619 targetUri = targetUri.buildUpon().appendQueryParameter( 1620 "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); 1621 Intent intent = new Intent(this, ReviewImage.class); 1622 intent.setData(targetUri); 1623 intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); 1624 intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); 1625 intent.putExtra("com.android.camera.ReviewMode", true); 1626 try { 1627 startActivity(intent); 1628 } catch (ActivityNotFoundException ex) { 1629 Log.e(TAG, "review image fail", ex); 1630 } 1631 } else { 1632 Log.e(TAG, "Can't view last image."); 1633 } 1634 } 1635 1636 private void startReceivingLocationUpdates() { 1637 if (mLocationManager != null) { 1638 try { 1639 mLocationManager.requestLocationUpdates( 1640 LocationManager.NETWORK_PROVIDER, 1641 1000, 1642 0F, 1643 mLocationListeners[1]); 1644 } catch (java.lang.SecurityException ex) { 1645 Log.i(TAG, "fail to request location update, ignore", ex); 1646 } catch (IllegalArgumentException ex) { 1647 Log.d(TAG, "provider does not exist " + ex.getMessage()); 1648 } 1649 try { 1650 mLocationManager.requestLocationUpdates( 1651 LocationManager.GPS_PROVIDER, 1652 1000, 1653 0F, 1654 mLocationListeners[0]); 1655 } catch (java.lang.SecurityException ex) { 1656 Log.i(TAG, "fail to request location update, ignore", ex); 1657 } catch (IllegalArgumentException ex) { 1658 Log.d(TAG, "provider does not exist " + ex.getMessage()); 1659 } 1660 } 1661 } 1662 1663 private void stopReceivingLocationUpdates() { 1664 if (mLocationManager != null) { 1665 for (int i = 0; i < mLocationListeners.length; i++) { 1666 try { 1667 mLocationManager.removeUpdates(mLocationListeners[i]); 1668 } catch (Exception ex) { 1669 Log.i(TAG, "fail to remove location listners, ignore", ex); 1670 } 1671 } 1672 } 1673 } 1674 1675 private Location getCurrentLocation() { 1676 // go in best to worst order 1677 for (int i = 0; i < mLocationListeners.length; i++) { 1678 Location l = mLocationListeners[i].current(); 1679 if (l != null) return l; 1680 } 1681 return null; 1682 } 1683 1684 private boolean isCameraIdle() { 1685 return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED; 1686 } 1687 1688 private boolean isImageCaptureIntent() { 1689 String action = getIntent().getAction(); 1690 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); 1691 } 1692 1693 private void showPostCaptureAlert() { 1694 if (mIsImageCaptureIntent) { 1695 findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE); 1696 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 1697 for (int id : pickIds) { 1698 View button = findViewById(id); 1699 ((View) button.getParent()).setVisibility(View.VISIBLE); 1700 } 1701 } 1702 } 1703 1704 private void hidePostCaptureAlert() { 1705 if (mIsImageCaptureIntent) { 1706 findViewById(R.id.shutter_button).setVisibility(View.VISIBLE); 1707 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 1708 for (int id : pickIds) { 1709 View button = findViewById(id); 1710 ((View) button.getParent()).setVisibility(View.GONE); 1711 } 1712 } 1713 } 1714 1715 private int calculatePicturesRemaining() { 1716 mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); 1717 return mPicturesRemaining; 1718 } 1719 1720 @Override 1721 public boolean onPrepareOptionsMenu(Menu menu) { 1722 super.onPrepareOptionsMenu(menu); 1723 // Only show the menu when camera is idle. 1724 for (int i = 0; i < menu.size(); i++) { 1725 menu.getItem(i).setVisible(isCameraIdle()); 1726 } 1727 1728 return true; 1729 } 1730 1731 @Override 1732 public boolean onCreateOptionsMenu(Menu menu) { 1733 super.onCreateOptionsMenu(menu); 1734 1735 if (mIsImageCaptureIntent) { 1736 // No options menu for attach mode. 1737 return false; 1738 } else { 1739 addBaseMenuItems(menu); 1740 } 1741 return true; 1742 } 1743 1744 private void addBaseMenuItems(Menu menu) { 1745 MenuItem gallery = menu.add(Menu.NONE, Menu.NONE, 1746 MenuHelper.POSITION_GOTO_GALLERY, 1747 R.string.camera_gallery_photos_text) 1748 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 1749 public boolean onMenuItemClick(MenuItem item) { 1750 gotoGallery(); 1751 return true; 1752 } 1753 }); 1754 gallery.setIcon(android.R.drawable.ic_menu_gallery); 1755 mGalleryItems.add(gallery); 1756 1757 MenuItem item = menu.add(Menu.NONE, Menu.NONE, 1758 MenuHelper.POSITION_CAMERA_SETTING, R.string.settings) 1759 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 1760 public boolean onMenuItemClick(MenuItem item) { 1761 if (mSettings == null) { 1762 mSettings = new OnScreenSettings( 1763 findViewById(R.id.camera_preview)); 1764 CameraSettings helper = 1765 new CameraSettings(Camera.this, mParameters); 1766 mSettings.setPreferenceScreen(helper 1767 .getPreferenceScreen(R.xml.camera_preferences)); 1768 } 1769 mSettings.setVisible(true); 1770 return true; 1771 } 1772 }); 1773 item.setIcon(android.R.drawable.ic_menu_preferences); 1774 } 1775 1776 public boolean onSwitchChanged(Switcher source, boolean onOff) { 1777 if (onOff == SWITCH_VIDEO) { 1778 if (!isCameraIdle()) return false; 1779 MenuHelper.gotoVideoMode(this); 1780 finish(); 1781 } 1782 return true; 1783 } 1784 1785 public boolean onFlashModeChanged(String modeString) { 1786 if (mPausing) return false; 1787 mParameters.setFlashMode(modeString); 1788 mCameraDevice.setParameters(mParameters); 1789 SharedPreferences.Editor editor = mPreferences.edit(); 1790 editor.putString(CameraSettings.KEY_FLASH_MODE, modeString); 1791 editor.commit(); 1792 return true; 1793 } 1794 1795 private void setCameraPictureSizeIfSupported(String sizeString) { 1796 List<Size> pictureSizes = mParameters.getSupportedPictureSizes(); 1797 if (pictureSizes != null) { 1798 int index = sizeString.indexOf('x'); 1799 int width = Integer.parseInt(sizeString.substring(0, index)); 1800 int height = Integer.parseInt(sizeString.substring(index + 1)); 1801 for (Size size: pictureSizes) { 1802 if (size.width == width && size.height == height) { 1803 mParameters.setPictureSize(width, height); 1804 break; 1805 } 1806 } 1807 } 1808 } 1809 1810 public void onSharedPreferenceChanged( 1811 SharedPreferences preferences, String key) { 1812 // ignore the events after "onPause()" 1813 if (mPausing) return; 1814 1815 if (CameraSettings.KEY_FLASH_MODE.equals(key)) { 1816 mParameters.setFlashMode(preferences.getString(key, "auto")); 1817 mCameraDevice.setParameters(mParameters); 1818 } else if (CameraSettings.KEY_FOCUS_MODE.equals(key)) { 1819 mFocusMode = preferences.getString(key, 1820 getString(R.string.pref_camera_focusmode_default)); 1821 } else if (CameraSettings.KEY_PICTURE_SIZE.equals(key)) { 1822 String pictureSize = preferences.getString(key, 1823 getString(R.string.pref_camera_picturesize_default)); 1824 setCameraPictureSizeIfSupported(pictureSize); 1825 mCameraDevice.setParameters(mParameters); 1826 } else if (CameraSettings.KEY_JPEG_QUALITY.equals(key)) { 1827 String jpegQuality = preferences.getString(key, 1828 getString(R.string.pref_camera_jpegquality_default)); 1829 mParameters.setJpegQuality(Integer.parseInt(jpegQuality)); 1830 mCameraDevice.setParameters(mParameters); 1831 } else if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) { 1832 mRecordLocation = preferences.getBoolean(key, false); 1833 if (mRecordLocation) { 1834 startReceivingLocationUpdates(); 1835 } else { 1836 stopReceivingLocationUpdates(); 1837 } 1838 } else if (CameraSettings.KEY_COLOR_EFFECT.equals(key)) { 1839 String colorEffect = preferences.getString(key, 1840 getString(R.string.pref_camera_coloreffect_default)); 1841 mParameters.setColorEffect(colorEffect); 1842 mCameraDevice.setParameters(mParameters); 1843 } else if (CameraSettings.KEY_WHITE_BALANCE.equals(key)) { 1844 String whiteBalance = preferences.getString(key, 1845 getString(R.string.pref_camera_whitebalance_default)); 1846 mParameters.setWhiteBalance(whiteBalance); 1847 mCameraDevice.setParameters(mParameters); 1848 } 1849 } 1850 1851} 1852 1853class FocusRectangle extends View { 1854 1855 @SuppressWarnings("unused") 1856 private static final String TAG = "FocusRectangle"; 1857 1858 public FocusRectangle(Context context, AttributeSet attrs) { 1859 super(context, attrs); 1860 } 1861 1862 private void setDrawable(int resid) { 1863 setBackgroundDrawable(getResources().getDrawable(resid)); 1864 } 1865 1866 public void showStart() { 1867 setDrawable(R.drawable.focus_focusing); 1868 } 1869 1870 public void showSuccess() { 1871 setDrawable(R.drawable.focus_focused); 1872 } 1873 1874 public void showFail() { 1875 setDrawable(R.drawable.focus_focus_failed); 1876 } 1877 1878 public void clear() { 1879 setBackgroundDrawable(null); 1880 } 1881} 1882 1883// FlashButton changes state every time it is clicked. 1884// The ModeChangeListener notifies that event. 1885class FlashButton extends ImageView implements View.OnClickListener { 1886 private static final String TAG = "FlashButton"; 1887 1888 private static final int MODE_OFF = 0; 1889 private static final int MODE_ON = 1; 1890 private static final int MODE_AUTO = 2; 1891 1892 private static final String[] MODE_STRINGS = new String[] { 1893 "off", "on", "auto" 1894 }; 1895 1896 private static final int[] FLASH_IMAGES = new int[] { 1897 R.drawable.flash_off, 1898 R.drawable.flash_on, 1899 R.drawable.flash_auto 1900 }; 1901 1902 private int mCurrentMode; 1903 private ModeChangeListener mListener; 1904 1905 public interface ModeChangeListener { 1906 // Returns true if the listener agrees to change mode. 1907 public boolean onFlashModeChanged(String modeString); 1908 } 1909 public FlashButton(Context context, AttributeSet attrs) { 1910 super(context, attrs); 1911 updateMode(MODE_AUTO); 1912 setOnClickListener(this); 1913 } 1914 1915 public void setMode(String modeString) { 1916 for (int i = 0; i < MODE_STRINGS.length; i++) { 1917 if (MODE_STRINGS[i].equals(modeString)) { 1918 updateModeIfNecessary(i); 1919 return; 1920 } 1921 } 1922 Log.w(TAG, "Unknown mode: " + modeString); 1923 } 1924 1925 public void setListener(ModeChangeListener listener) { 1926 mListener = listener; 1927 } 1928 1929 public void onClick(View v) { 1930 int nextMode = (mCurrentMode + 1) % FLASH_IMAGES.length; 1931 updateMode(nextMode); 1932 } 1933 1934 private void updateModeIfNecessary(int mode) { 1935 if (mode == mCurrentMode) return; 1936 if (mode < 0 || mode >= FLASH_IMAGES.length) { 1937 return; 1938 } 1939 updateMode(mode); 1940 } 1941 1942 private void updateMode(int mode) { 1943 if (mListener == null) return; 1944 if (!mListener.onFlashModeChanged(MODE_STRINGS[mode])) return; 1945 mCurrentMode = mode; 1946 setImageResource(FLASH_IMAGES[mode]); 1947 } 1948} 1949