Camera.java revision 640ad87bf4945f5baa22ef1e02eb1c4ac7fd3ef7
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 public static Matrix getDisplayMatrix(Bitmap b, ImageView v) { 707 Matrix m = new Matrix(); 708 float bw = b.getWidth(); 709 float bh = b.getHeight(); 710 float vw = v.getWidth(); 711 float vh = v.getHeight(); 712 float scale, x, y; 713 if (bw * vh > vw * bh) { 714 scale = vh / bh; 715 x = (vw - scale * bw) * 0.5F; 716 y = 0; 717 } else { 718 scale = vw / bw; 719 x = 0; 720 y = (vh - scale * bh) * 0.5F; 721 } 722 m.setScale(scale, scale, 0.5F, 0.5F); 723 m.postTranslate(x, y); 724 return m; 725 } 726 727 @Override 728 public void onCreate(Bundle icicle) { 729 super.onCreate(icicle); 730 731 Window win = getWindow(); 732 win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 733 setContentView(R.layout.camera); 734 mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); 735 mViewFinderWidth = mSurfaceView.getLayoutParams().width; 736 mViewFinderHeight = mSurfaceView.getLayoutParams().height; 737 mPreferences = PreferenceManager.getDefaultSharedPreferences(this); 738 739 /* 740 * To reduce startup time, we start the preview in another thread. 741 * We make sure the preview is started at the end of onCreate. 742 */ 743 Thread startPreviewThread = new Thread(new Runnable() { 744 public void run() { 745 startPreview(); 746 } 747 }); 748 startPreviewThread.start(); 749 750 // don't set mSurfaceHolder here. We have it set ONLY within 751 // surfaceChanged / surfaceDestroyed, other parts of the code 752 // assume that when it is set, the surface is also set. 753 SurfaceHolder holder = mSurfaceView.getHolder(); 754 holder.addCallback(this); 755 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 756 757 mIsImageCaptureIntent = isImageCaptureIntent(); 758 LayoutInflater inflater = getLayoutInflater(); 759 760 ViewGroup rootView = (ViewGroup) findViewById(R.id.camera); 761 if (mIsImageCaptureIntent) { 762 View controlBar = inflater.inflate( 763 R.layout.attach_camera_control, rootView); 764 controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this); 765 controlBar.findViewById(R.id.btn_retake).setOnClickListener(this); 766 controlBar.findViewById(R.id.btn_done).setOnClickListener(this); 767 } else { 768 inflater.inflate(R.layout.camera_control, rootView); 769 mSwitcher = ((Switcher) findViewById(R.id.camera_switch)); 770 mSwitcher.setOnSwitchListener(this); 771 } 772 773 // Make sure preview is started. 774 try { 775 startPreviewThread.join(); 776 } catch (InterruptedException ex) { 777 // ignore 778 } 779 } 780 781 @Override 782 public void onStart() { 783 super.onStart(); 784 if (!mIsImageCaptureIntent) { 785 mSwitcher.setSwitch(SWITCH_CAMERA); 786 } 787 } 788 789 private void checkStorage() { 790 if (ImageManager.isMediaScannerScanning(getContentResolver())) { 791 mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; 792 } else { 793 calculatePicturesRemaining(); 794 } 795 updateStorageHint(mPicturesRemaining); 796 } 797 798 public void onClick(View v) { 799 switch (v.getId()) { 800 case R.id.btn_retake: 801 hidePostCaptureAlert(); 802 restartPreview(); 803 break; 804 case R.id.review_thumbnail: 805 if (isCameraIdle()) { 806 viewLastImage(); 807 } 808 break; 809 case R.id.btn_done: 810 doAttach(); 811 break; 812 case R.id.btn_cancel: 813 doCancel(); 814 } 815 } 816 817 private void doAttach() { 818 if (mPausing) { 819 return; 820 } 821 Bitmap bitmap = mImageCapture.getLastBitmap(); 822 823 String cropValue = null; 824 Uri saveUri = null; 825 826 Bundle myExtras = getIntent().getExtras(); 827 if (myExtras != null) { 828 saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 829 cropValue = myExtras.getString("crop"); 830 } 831 832 833 if (cropValue == null) { 834 // First handle the no crop case -- just return the value. If the 835 // caller specifies a "save uri" then write the data to it's 836 // stream. Otherwise, pass back a scaled down version of the bitmap 837 // directly in the extras. 838 if (saveUri != null) { 839 OutputStream outputStream = null; 840 try { 841 outputStream = mContentResolver.openOutputStream(saveUri); 842 bitmap.compress(Bitmap.CompressFormat.JPEG, 75, 843 outputStream); 844 outputStream.close(); 845 846 setResult(RESULT_OK); 847 finish(); 848 } catch (IOException ex) { 849 // ignore exception 850 } finally { 851 if (outputStream != null) { 852 try { 853 outputStream.close(); 854 } catch (IOException ex) { 855 // ignore exception 856 } 857 } 858 } 859 } else { 860 float scale = .5F; 861 Matrix m = new Matrix(); 862 m.setScale(scale, scale); 863 864 bitmap = Bitmap.createBitmap(bitmap, 0, 0, 865 bitmap.getWidth(), 866 bitmap.getHeight(), 867 m, true); 868 869 setResult(RESULT_OK, 870 new Intent("inline-data").putExtra("data", bitmap)); 871 finish(); 872 } 873 } else { 874 // Save the image to a temp file and invoke the cropper 875 Uri tempUri = null; 876 FileOutputStream tempStream = null; 877 try { 878 File path = getFileStreamPath(sTempCropFilename); 879 path.delete(); 880 tempStream = openFileOutput(sTempCropFilename, 0); 881 bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); 882 tempStream.close(); 883 tempUri = Uri.fromFile(path); 884 } catch (FileNotFoundException ex) { 885 setResult(Activity.RESULT_CANCELED); 886 finish(); 887 return; 888 } catch (IOException ex) { 889 setResult(Activity.RESULT_CANCELED); 890 finish(); 891 return; 892 } finally { 893 if (tempStream != null) { 894 try { 895 tempStream.close(); 896 } catch (IOException ex) { 897 // ignore exception 898 } 899 } 900 } 901 902 Bundle newExtras = new Bundle(); 903 if (cropValue.equals("circle")) { 904 newExtras.putString("circleCrop", "true"); 905 } 906 if (saveUri != null) { 907 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); 908 } else { 909 newExtras.putBoolean("return-data", true); 910 } 911 newExtras.putBoolean(MediaStore.EXTRA_FULL_SCREEN, true); 912 913 Intent cropIntent = new Intent(); 914 cropIntent.setClass(Camera.this, CropImage.class); 915 cropIntent.setData(tempUri); 916 cropIntent.putExtras(newExtras); 917 918 startActivityForResult(cropIntent, CROP_MSG); 919 } 920 } 921 922 private void doCancel() { 923 setResult(RESULT_CANCELED, new Intent()); 924 finish(); 925 } 926 927 public void onShutterButtonFocus(ShutterButton button, boolean pressed) { 928 if (mPausing) { 929 return; 930 } 931 switch (button.getId()) { 932 case R.id.shutter_button: 933 doFocus(pressed); 934 break; 935 } 936 } 937 938 public void onShutterButtonClick(ShutterButton button) { 939 if (mPausing) { 940 return; 941 } 942 switch (button.getId()) { 943 case R.id.shutter_button: 944 doSnap(); 945 break; 946 } 947 } 948 949 private void updateStorageHint() { 950 updateStorageHint(MenuHelper.calculatePicturesRemaining()); 951 } 952 953 private OnScreenHint mStorageHint; 954 955 private void updateStorageHint(int remaining) { 956 String noStorageText = null; 957 958 if (remaining == MenuHelper.NO_STORAGE_ERROR) { 959 String state = Environment.getExternalStorageState(); 960 if (state == Environment.MEDIA_CHECKING || 961 ImageManager.isMediaScannerScanning(getContentResolver())) { 962 noStorageText = getString(R.string.preparing_sd); 963 } else { 964 noStorageText = getString(R.string.no_storage); 965 } 966 } else if (remaining < 1) { 967 noStorageText = getString(R.string.not_enough_space); 968 } 969 970 if (noStorageText != null) { 971 if (mStorageHint == null) { 972 mStorageHint = OnScreenHint.makeText(this, noStorageText); 973 } else { 974 mStorageHint.setText(noStorageText); 975 } 976 mStorageHint.show(); 977 } else if (mStorageHint != null) { 978 mStorageHint.cancel(); 979 mStorageHint = null; 980 } 981 } 982 983 void installIntentFilter() { 984 // install an intent filter to receive SD card related events. 985 IntentFilter intentFilter = 986 new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); 987 intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); 988 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); 989 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); 990 intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); 991 intentFilter.addDataScheme("file"); 992 registerReceiver(mReceiver, intentFilter); 993 mDidRegister = true; 994 } 995 996 void initializeFocusTone() { 997 // Initialize focus tone generator. 998 try { 999 mFocusToneGenerator = new ToneGenerator( 1000 AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); 1001 } catch (Throwable ex) { 1002 Log.w(TAG, "Exception caught while creating tone generator: ", ex); 1003 mFocusToneGenerator = null; 1004 } 1005 } 1006 1007 void readPreference() { 1008 mRecordLocation = mPreferences.getBoolean( 1009 "pref_camera_recordlocation_key", false); 1010 mFocusMode = mPreferences.getString( 1011 CameraSettings.KEY_FOCUS_MODE, 1012 getString(R.string.pref_camera_focusmode_default)); 1013 } 1014 1015 @Override 1016 public void onResume() { 1017 super.onResume(); 1018 1019 mPausing = false; 1020 mJpegPictureCallbackTime = 0; 1021 mImageCapture = new ImageCapture(); 1022 1023 // Start the preview if it is not started. 1024 if (!mPreviewing) { 1025 startPreview(); 1026 } 1027 1028 if (mSurfaceHolder != null) { 1029 // If first time initialization is not finished, put it in the 1030 // message queue. 1031 if (!mFirstTimeInitialized) { 1032 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1033 } else { 1034 initializeSecondTime(); 1035 } 1036 } 1037 1038 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 1039 } 1040 1041 private static ImageManager.DataLocation dataLocation() { 1042 return ImageManager.DataLocation.EXTERNAL; 1043 } 1044 1045 @Override 1046 protected void onPause() { 1047 mPausing = true; 1048 stopPreview(); 1049 // Close the camera now because other activities may need to use it. 1050 closeCamera(); 1051 1052 if (mFirstTimeInitialized) { 1053 mOrientationListener.disable(); 1054 mGpsIndicator.setVisibility(View.INVISIBLE); 1055 if (!mIsImageCaptureIntent) { 1056 mThumbController.storeData( 1057 ImageManager.getLastImageThumbPath()); 1058 } 1059 hidePostCaptureAlert(); 1060 } 1061 1062 if (mDidRegister) { 1063 unregisterReceiver(mReceiver); 1064 mDidRegister = false; 1065 } 1066 stopReceivingLocationUpdates(); 1067 1068 if (mFocusToneGenerator != null) { 1069 mFocusToneGenerator.release(); 1070 mFocusToneGenerator = null; 1071 } 1072 1073 if (mStorageHint != null) { 1074 mStorageHint.cancel(); 1075 mStorageHint = null; 1076 } 1077 1078 // If we are in an image capture intent and has taken 1079 // a picture, we just clear it in onPause. 1080 mImageCapture.clearLastBitmap(); 1081 mImageCapture = null; 1082 1083 // This is necessary to make the ZoomButtonsController unregister 1084 // its configuration change receiver. 1085 if (mZoomButtons != null) { 1086 mZoomButtons.setVisible(false); 1087 } 1088 1089 // Remove the messages in the event queue. 1090 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 1091 mHandler.removeMessages(RESTART_PREVIEW); 1092 mHandler.removeMessages(FIRST_TIME_INIT); 1093 1094 super.onPause(); 1095 } 1096 1097 @Override 1098 protected void onActivityResult( 1099 int requestCode, int resultCode, Intent data) { 1100 switch (requestCode) { 1101 case CROP_MSG: { 1102 Intent intent = new Intent(); 1103 if (data != null) { 1104 Bundle extras = data.getExtras(); 1105 if (extras != null) { 1106 intent.putExtras(extras); 1107 } 1108 } 1109 setResult(resultCode, intent); 1110 finish(); 1111 1112 File path = getFileStreamPath(sTempCropFilename); 1113 path.delete(); 1114 1115 break; 1116 } 1117 } 1118 } 1119 1120 private void autoFocus() { 1121 // Initiate autofocus only when preview is started and snapshot is not 1122 // in progress. 1123 if (isCameraIdle() && mPreviewing) { 1124 Log.v(TAG, "Start autofocus."); 1125 if (mZoomButtons != null) mZoomButtons.setVisible(false); 1126 mFocusStartTime = System.currentTimeMillis(); 1127 mFocusState = FOCUSING; 1128 updateFocusIndicator(); 1129 mCameraDevice.autoFocus(mAutoFocusCallback); 1130 } 1131 } 1132 1133 private void clearFocusState() { 1134 mFocusState = FOCUS_NOT_STARTED; 1135 updateFocusIndicator(); 1136 } 1137 1138 private void updateFocusIndicator() { 1139 if (mFocusRectangle == null) return; 1140 1141 if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) { 1142 mFocusRectangle.showStart(); 1143 } else if (mFocusState == FOCUS_SUCCESS) { 1144 mFocusRectangle.showSuccess(); 1145 } else if (mFocusState == FOCUS_FAIL) { 1146 mFocusRectangle.showFail(); 1147 } else { 1148 mFocusRectangle.clear(); 1149 } 1150 } 1151 1152 @Override 1153 public boolean onKeyDown(int keyCode, KeyEvent event) { 1154 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 1155 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1156 1157 switch (keyCode) { 1158 case KeyEvent.KEYCODE_BACK: 1159 if (!isCameraIdle()) { 1160 // ignore backs while we're taking a picture 1161 return true; 1162 } 1163 break; 1164 case KeyEvent.KEYCODE_FOCUS: 1165 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1166 doFocus(true); 1167 } 1168 return true; 1169 case KeyEvent.KEYCODE_CAMERA: 1170 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1171 doSnap(); 1172 } 1173 return true; 1174 case KeyEvent.KEYCODE_DPAD_CENTER: 1175 // If we get a dpad center event without any focused view, move 1176 // the focus to the shutter button and press it. 1177 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1178 // Start auto-focus immediately to reduce shutter lag. After 1179 // the shutter button gets the focus, doFocus() will be 1180 // called again but it is fine. 1181 doFocus(true); 1182 if (mShutterButton.isInTouchMode()) { 1183 mShutterButton.requestFocusFromTouch(); 1184 } else { 1185 mShutterButton.requestFocus(); 1186 } 1187 mShutterButton.setPressed(true); 1188 } 1189 return true; 1190 } 1191 1192 return super.onKeyDown(keyCode, event); 1193 } 1194 1195 @Override 1196 public boolean onKeyUp(int keyCode, KeyEvent event) { 1197 switch (keyCode) { 1198 case KeyEvent.KEYCODE_FOCUS: 1199 if (mFirstTimeInitialized) { 1200 doFocus(false); 1201 } 1202 return true; 1203 } 1204 return super.onKeyUp(keyCode, event); 1205 } 1206 1207 @Override 1208 public boolean onTouchEvent(MotionEvent event) { 1209 switch (event.getAction()) { 1210 case MotionEvent.ACTION_DOWN: 1211 // Show zoom buttons only when preview is started and snapshot 1212 // is not in progress. mZoomButtons may be null if it is not 1213 // initialized. 1214 if (!mPausing && isCameraIdle() && mPreviewing 1215 && mZoomButtons != null) { 1216 mZoomButtons.setVisible(true); 1217 } 1218 return true; 1219 } 1220 return super.onTouchEvent(event); 1221 } 1222 1223 private void doSnap() { 1224 // If the user has half-pressed the shutter and focus is completed, we 1225 // can take the photo right away. If the focus mode is infinity, we can 1226 // also take the photo. 1227 if (mFocusMode.equals(getString( 1228 R.string.pref_camera_focusmode_value_infinity)) 1229 || (mFocusState == FOCUS_SUCCESS 1230 || mFocusState == FOCUS_FAIL)) { 1231 if (mZoomButtons != null) mZoomButtons.setVisible(false); 1232 mImageCapture.onSnap(); 1233 } else if (mFocusState == FOCUSING) { 1234 // Half pressing the shutter (i.e. the focus button event) will 1235 // already have requested AF for us, so just request capture on 1236 // focus here. 1237 mFocusState = FOCUSING_SNAP_ON_FINISH; 1238 } else if (mFocusState == FOCUS_NOT_STARTED) { 1239 // Focus key down event is dropped for some reasons. Just ignore. 1240 } 1241 } 1242 1243 private void doFocus(boolean pressed) { 1244 // Do the focus if the mode is auto. No focus needed in infinity mode. 1245 if (mFocusMode.equals(getString( 1246 R.string.pref_camera_focusmode_value_auto))) { 1247 if (pressed) { // Focus key down. 1248 autoFocus(); 1249 } else { // Focus key up. 1250 if (mFocusState != FOCUSING_SNAP_ON_FINISH) { 1251 // User releases half-pressed focus key. 1252 clearFocusState(); 1253 } 1254 } 1255 } 1256 } 1257 1258 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1259 // Make sure we have a surface in the holder before proceeding. 1260 if (holder.getSurface() == null) { 1261 Log.d(TAG, "holder.getSurface() == null"); 1262 return; 1263 } 1264 1265 mSurfaceHolder = holder; 1266 mViewFinderWidth = w; 1267 mViewFinderHeight = h; 1268 1269 // Sometimes surfaceChanged is called after onPause. Ignore it. 1270 if (mPausing) return; 1271 1272 // Set preview display if the surface is being created. Preview was 1273 // already started. 1274 if (holder.isCreating()) { 1275 setPreviewDisplay(holder); 1276 } 1277 1278 // If first time initialization is not finished, send a message to do 1279 // it later. We want to finish surfaceChanged as soon as possible to let 1280 // user see preview first. 1281 if (!mFirstTimeInitialized) { 1282 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1283 } else { 1284 initializeSecondTime(); 1285 } 1286 } 1287 1288 public void surfaceCreated(SurfaceHolder holder) { 1289 } 1290 1291 public void surfaceDestroyed(SurfaceHolder holder) { 1292 stopPreview(); 1293 mSurfaceHolder = null; 1294 } 1295 1296 private void closeCamera() { 1297 if (mCameraDevice != null) { 1298 CameraHolder.instance().release(); 1299 mCameraDevice = null; 1300 mPreviewing = false; 1301 } 1302 } 1303 1304 private boolean ensureCameraDevice() { 1305 if (mCameraDevice == null) { 1306 mCameraDevice = CameraHolder.instance().open(); 1307 } 1308 return mCameraDevice != null; 1309 } 1310 1311 private void updateLastImage() { 1312 IImageList list = ImageManager.allImages( 1313 mContentResolver, 1314 dataLocation(), 1315 ImageManager.INCLUDE_IMAGES, 1316 ImageManager.SORT_ASCENDING, 1317 ImageManager.CAMERA_IMAGE_BUCKET_ID); 1318 int count = list.getCount(); 1319 if (count > 0) { 1320 IImage image = list.getImageAt(count - 1); 1321 Uri uri = image.fullSizeImageUri(); 1322 mThumbController.setData(uri, image.miniThumbBitmap()); 1323 } else { 1324 mThumbController.setData(null, null); 1325 } 1326 list.deactivate(); 1327 } 1328 1329 private void restartPreview() { 1330 // make sure the surfaceview fills the whole screen when previewing 1331 mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE); 1332 startPreview(); 1333 1334 // Calculate this in advance of each shot so we don't add to shutter 1335 // latency. It's true that someone else could write to the SD card in 1336 // the mean time and fill it, but that could have happened between the 1337 // shutter press and saving the JPEG too. 1338 calculatePicturesRemaining(); 1339 } 1340 1341 private void setPreviewDisplay(SurfaceHolder holder) { 1342 try { 1343 mCameraDevice.setPreviewDisplay(holder); 1344 } catch (Throwable ex) { 1345 closeCamera(); 1346 throw new RuntimeException("setPreviewDisplay failed", ex); 1347 } 1348 } 1349 1350 private void startPreview() { 1351 if (mPausing) return; 1352 1353 if (!ensureCameraDevice()) return; 1354 1355 if (isFinishing()) return; 1356 1357 // If we're previewing already, stop the preview first (this will blank 1358 // the screen). 1359 if (mPreviewing) stopPreview(); 1360 1361 setPreviewDisplay(mSurfaceHolder); 1362 1363 setCameraParameter(); 1364 1365 final long wallTimeStart = SystemClock.elapsedRealtime(); 1366 final long threadTimeStart = Debug.threadCpuTimeNanos(); 1367 1368 // Set one shot preview callback for latency measurement. 1369 mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback); 1370 mCameraDevice.setErrorCallback(mErrorCallback); 1371 1372 try { 1373 Log.v(TAG, "startPreview"); 1374 mCameraDevice.startPreview(); 1375 } catch (Throwable ex) { 1376 closeCamera(); 1377 throw new RuntimeException("startPreview failed", ex); 1378 } 1379 mPreviewing = true; 1380 mStatus = IDLE; 1381 1382 long threadTimeEnd = Debug.threadCpuTimeNanos(); 1383 long wallTimeEnd = SystemClock.elapsedRealtime(); 1384 if ((wallTimeEnd - wallTimeStart) > 3000) { 1385 Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) 1386 + " ms. Thread time was" 1387 + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); 1388 } 1389 } 1390 1391 private void stopPreview() { 1392 if (mCameraDevice != null && mPreviewing) { 1393 Log.v(TAG, "stopPreview"); 1394 mCameraDevice.stopPreview(); 1395 } 1396 mPreviewing = false; 1397 // If auto focus was in progress, it would have been canceled. 1398 clearFocusState(); 1399 } 1400 1401 private void setCameraParameter() { 1402 // request the preview size, the hardware may not honor it, 1403 // if we depended on it we would have to query the size again 1404 mParameters = mCameraDevice.getParameters(); 1405 mParameters.setPreviewSize(mViewFinderWidth, mViewFinderHeight); 1406 1407 // Set picture size parameter. 1408 String pictureSize = mPreferences.getString( 1409 CameraSettings.KEY_PICTURE_SIZE, 1410 getString(R.string.pref_camera_picturesize_default)); 1411 mParameters.set(PARM_PICTURE_SIZE, pictureSize); 1412 1413 // Set JPEG quality parameter. 1414 String jpegQuality = mPreferences.getString( 1415 CameraSettings.KEY_JPEG_QUALITY, 1416 getString(R.string.pref_camera_jpegquality_default)); 1417 mParameters.set(PARM_JPEG_QUALITY, jpegQuality); 1418 1419 mCameraDevice.setParameters(mParameters); 1420 } 1421 1422 void gotoGallery() { 1423 MenuHelper.gotoCameraImageGallery(this); 1424 } 1425 1426 private void viewLastImage() { 1427 if (mThumbController.isUriValid()) { 1428 Uri targetUri = mThumbController.getUri(); 1429 targetUri = targetUri.buildUpon().appendQueryParameter( 1430 "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); 1431 Intent intent = new Intent(this, ReviewImage.class); 1432 intent.setData(targetUri); 1433 intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); 1434 intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); 1435 intent.putExtra("com.android.camera.ReviewMode", true); 1436 try { 1437 startActivity(intent); 1438 } catch (ActivityNotFoundException ex) { 1439 Log.e(TAG, "review image fail", ex); 1440 } 1441 } else { 1442 Log.e(TAG, "Can't view last image."); 1443 } 1444 } 1445 1446 private void startReceivingLocationUpdates() { 1447 if (mLocationManager != null) { 1448 try { 1449 mLocationManager.requestLocationUpdates( 1450 LocationManager.NETWORK_PROVIDER, 1451 1000, 1452 0F, 1453 mLocationListeners[1]); 1454 } catch (java.lang.SecurityException ex) { 1455 Log.i(TAG, "fail to request location update, ignore", ex); 1456 } catch (IllegalArgumentException ex) { 1457 Log.d(TAG, "provider does not exist " + ex.getMessage()); 1458 } 1459 try { 1460 mLocationManager.requestLocationUpdates( 1461 LocationManager.GPS_PROVIDER, 1462 1000, 1463 0F, 1464 mLocationListeners[0]); 1465 } catch (java.lang.SecurityException ex) { 1466 Log.i(TAG, "fail to request location update, ignore", ex); 1467 } catch (IllegalArgumentException ex) { 1468 Log.d(TAG, "provider does not exist " + ex.getMessage()); 1469 } 1470 } 1471 } 1472 1473 private void stopReceivingLocationUpdates() { 1474 if (mLocationManager != null) { 1475 for (int i = 0; i < mLocationListeners.length; i++) { 1476 try { 1477 mLocationManager.removeUpdates(mLocationListeners[i]); 1478 } catch (Exception ex) { 1479 Log.i(TAG, "fail to remove location listners, ignore", ex); 1480 } 1481 } 1482 } 1483 } 1484 1485 private Location getCurrentLocation() { 1486 // go in best to worst order 1487 for (int i = 0; i < mLocationListeners.length; i++) { 1488 Location l = mLocationListeners[i].current(); 1489 if (l != null) return l; 1490 } 1491 return null; 1492 } 1493 1494 private boolean isCameraIdle() { 1495 return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED; 1496 } 1497 1498 private boolean isImageCaptureIntent() { 1499 String action = getIntent().getAction(); 1500 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); 1501 } 1502 1503 private void showPostCaptureAlert() { 1504 if (mIsImageCaptureIntent) { 1505 findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE); 1506 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 1507 for (int id : pickIds) { 1508 View button = findViewById(id); 1509 ((View) button.getParent()).setVisibility(View.VISIBLE); 1510 } 1511 } 1512 } 1513 1514 private void hidePostCaptureAlert() { 1515 if (mIsImageCaptureIntent) { 1516 findViewById(R.id.shutter_button).setVisibility(View.VISIBLE); 1517 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 1518 for (int id : pickIds) { 1519 View button = findViewById(id); 1520 ((View) button.getParent()).setVisibility(View.GONE); 1521 } 1522 } 1523 } 1524 1525 private int calculatePicturesRemaining() { 1526 mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); 1527 return mPicturesRemaining; 1528 } 1529 1530 @Override 1531 public boolean onPrepareOptionsMenu(Menu menu) { 1532 super.onPrepareOptionsMenu(menu); 1533 1534 for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { 1535 menu.setGroupVisible(i, false); 1536 } 1537 1538 // Only show the menu when camera is idle. 1539 if (isCameraIdle()) { 1540 menu.setGroupVisible(MenuHelper.GENERIC_ITEM, true); 1541 menu.setGroupVisible(MenuHelper.IMAGE_MODE_ITEM, true); 1542 } 1543 1544 return true; 1545 } 1546 1547 @Override 1548 public boolean onCreateOptionsMenu(Menu menu) { 1549 super.onCreateOptionsMenu(menu); 1550 1551 if (mIsImageCaptureIntent) { 1552 // No options menu for attach mode. 1553 return false; 1554 } else { 1555 addBaseMenuItems(menu); 1556 } 1557 return true; 1558 } 1559 1560 private void addBaseMenuItems(Menu menu) { 1561 MenuHelper.addSwitchModeMenuItem(menu, this, true); 1562 { 1563 MenuItem gallery = menu.add( 1564 MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, 1565 R.string.camera_gallery_photos_text) 1566 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 1567 public boolean onMenuItemClick(MenuItem item) { 1568 gotoGallery(); 1569 return true; 1570 } 1571 }); 1572 gallery.setIcon(android.R.drawable.ic_menu_gallery); 1573 mGalleryItems.add(gallery); 1574 } 1575 { 1576 MenuItem gallery = menu.add( 1577 MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, 1578 R.string.camera_gallery_photos_text) 1579 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 1580 public boolean onMenuItemClick(MenuItem item) { 1581 gotoGallery(); 1582 return true; 1583 } 1584 }); 1585 gallery.setIcon(android.R.drawable.ic_menu_gallery); 1586 mGalleryItems.add(gallery); 1587 } 1588 1589 MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 1590 0, R.string.settings) 1591 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 1592 public boolean onMenuItemClick(MenuItem item) { 1593 // Keep the camera instance for a while. 1594 // This avoids re-opening the camera and saves time. 1595 CameraHolder.instance().keep(); 1596 1597 Intent intent = new Intent(); 1598 intent.setClass(Camera.this, CameraSettings.class); 1599 startActivity(intent); 1600 return true; 1601 } 1602 }); 1603 item.setIcon(android.R.drawable.ic_menu_preferences); 1604 } 1605 1606 public boolean onSwitchChanged(Switcher source, boolean onOff) { 1607 if (onOff == SWITCH_VIDEO) { 1608 if (!isCameraIdle()) return false; 1609 MenuHelper.gotoVideoMode(this); 1610 finish(); 1611 } 1612 return true; 1613 } 1614} 1615 1616class FocusRectangle extends View { 1617 1618 @SuppressWarnings("unused") 1619 private static final String TAG = "FocusRectangle"; 1620 1621 public FocusRectangle(Context context, AttributeSet attrs) { 1622 super(context, attrs); 1623 } 1624 1625 private void setDrawable(int resid) { 1626 setBackgroundDrawable(getResources().getDrawable(resid)); 1627 } 1628 1629 public void showStart() { 1630 setDrawable(R.drawable.focus_focusing); 1631 } 1632 1633 public void showSuccess() { 1634 setDrawable(R.drawable.focus_focused); 1635 } 1636 1637 public void showFail() { 1638 setDrawable(R.drawable.focus_focus_failed); 1639 } 1640 1641 public void clear() { 1642 setBackgroundDrawable(null); 1643 } 1644} 1645