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