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