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