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