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