Camera.java revision 9a2b75b19b46ad5a66edf9a1c97f8da281c3dfdc
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.camera; 18 19import com.android.camera.gallery.IImage; 20import com.android.camera.gallery.IImageList; 21import com.android.camera.ui.BasicSettingPicker; 22import com.android.camera.ui.CameraHeadUpDisplay; 23import com.android.camera.ui.GLRootView; 24import com.android.camera.ui.HeadUpDisplay; 25import com.android.camera.ui.ControlPanel; 26import com.android.camera.ui.ZoomControllerListener; 27 28import android.app.Activity; 29import android.content.ActivityNotFoundException; 30import android.content.BroadcastReceiver; 31import android.content.ContentProviderClient; 32import android.content.ContentResolver; 33import android.content.Context; 34import android.content.Intent; 35import android.content.IntentFilter; 36import android.content.SharedPreferences.Editor; 37import android.content.res.Configuration; 38import android.content.res.Resources; 39import android.database.Cursor; 40import android.graphics.Bitmap; 41import android.graphics.BitmapFactory; 42import android.hardware.Camera.CameraInfo; 43import android.hardware.Camera.Parameters; 44import android.hardware.Camera.PictureCallback; 45import android.hardware.Camera.Size; 46import android.location.Location; 47import android.location.LocationManager; 48import android.location.LocationProvider; 49import android.media.AudioManager; 50import android.media.CameraProfile; 51import android.media.ToneGenerator; 52import android.net.Uri; 53import android.os.Build; 54import android.os.Bundle; 55import android.os.Environment; 56import android.os.Handler; 57import android.os.Looper; 58import android.os.Message; 59import android.os.MessageQueue; 60import android.provider.MediaStore; 61import android.provider.Settings; 62import android.provider.MediaStore.Images.ImageColumns; 63import android.provider.MediaStore.Images.Media; 64import android.util.AttributeSet; 65import android.util.Log; 66import android.view.GestureDetector; 67import android.view.KeyEvent; 68import android.view.LayoutInflater; 69import android.view.Menu; 70import android.view.MenuItem; 71import android.view.MotionEvent; 72import android.view.OrientationEventListener; 73import android.view.SurfaceHolder; 74import android.view.SurfaceView; 75import android.view.View; 76import android.view.ViewGroup; 77import android.view.ViewStub; 78import android.view.Window; 79import android.view.WindowManager; 80import android.view.MenuItem.OnMenuItemClickListener; 81import android.widget.AdapterView; 82import android.widget.AdapterView.OnItemClickListener; 83import android.widget.Button; 84import android.widget.CursorAdapter; 85import android.widget.FrameLayout; 86import android.widget.ListView; 87 88import java.io.File; 89import java.io.FileNotFoundException; 90import java.io.FileOutputStream; 91import java.io.IOException; 92import java.io.OutputStream; 93import java.text.SimpleDateFormat; 94import java.util.ArrayList; 95import java.util.Collections; 96import java.util.Date; 97import java.util.HashMap; 98import java.util.List; 99 100/** The Camera activity which can preview and take pictures. */ 101public class Camera extends NoSearchActivity implements View.OnClickListener, 102 ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, 103 Switcher.OnSwitchListener { 104 105 private static final String TAG = "camera"; 106 107 private static final int CROP_MSG = 1; 108 private static final int FIRST_TIME_INIT = 2; 109 private static final int RESTART_PREVIEW = 3; 110 private static final int CLEAR_SCREEN_DELAY = 4; 111 private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 5; 112 113 // The subset of parameters we need to update in setCameraParameters(). 114 private static final int UPDATE_PARAM_INITIALIZE = 1; 115 private static final int UPDATE_PARAM_ZOOM = 2; 116 private static final int UPDATE_PARAM_PREFERENCE = 4; 117 private static final int UPDATE_PARAM_ALL = -1; 118 119 // When setCameraParametersWhenIdle() is called, we accumulate the subsets 120 // needed to be updated in mUpdateSet. 121 private int mUpdateSet; 122 123 // The brightness settings used when it is set to automatic in the system. 124 // The reason why it is set to 0.7 is just because 1.0 is too bright. 125 private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f; 126 127 private static final int SCREEN_DELAY = 2 * 60 * 1000; 128 private static final int FOCUS_BEEP_VOLUME = 100; 129 130 private static final int ZOOM_STOPPED = 0; 131 private static final int ZOOM_START = 1; 132 private static final int ZOOM_STOPPING = 2; 133 134 private int mZoomState = ZOOM_STOPPED; 135 private boolean mSmoothZoomSupported = false; 136 private int mZoomValue; // The current zoom value. 137 private int mZoomMax; 138 private int mTargetZoomValue; 139 private ZoomPicker mZoomPicker; 140 141 private Parameters mParameters; 142 private Parameters mInitialParams; 143 144 private MyOrientationEventListener mOrientationListener; 145 // The device orientation in degrees. Default is unknown. 146 private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; 147 // The orientation compensation for icons and thumbnails. 148 private int mOrientationCompensation = 0; 149 private ComboPreferences mPreferences; 150 151 private static final int IDLE = 1; 152 private static final int SNAPSHOT_IN_PROGRESS = 2; 153 154 private static final boolean SWITCH_CAMERA = true; 155 private static final boolean SWITCH_VIDEO = false; 156 157 private int mStatus = IDLE; 158 private static final String sTempCropFilename = "crop-temp"; 159 160 private android.hardware.Camera mCameraDevice; 161 private ContentProviderClient mMediaProviderClient; 162 private SurfaceView mSurfaceView; 163 private SurfaceHolder mSurfaceHolder = null; 164 private ShutterButton mShutterButton; 165 private FocusRectangle mFocusRectangle; 166 private ToneGenerator mFocusToneGenerator; 167 private GestureDetector mGestureDetector; 168 private Switcher mSwitcher; 169 private boolean mStartPreviewFail = false; 170 171 private GLRootView mGLRootView; 172 173 // The layouts of small devices have a thumbnail button, which shows the last 174 // captured picture. 175 private RotateImageView mThumbnailButton; 176 // The layouts of xlarge devices have a list of thumbnails, which show the 177 // last captured pictures. 178 private ListView mThumbnailList; 179 private OnItemClickListener mThumbnailItemClickListener = 180 new ThumbnailItemClickListener(); 181 private ThumbnailAdapter mThumbnailAdapter; 182 183 // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true. 184 private String mCropValue; 185 private Uri mSaveUri; 186 187 private ImageCapture mImageCapture = null; 188 189 /** 190 * An unpublished intent flag requesting to return as soon as capturing 191 * is completed. 192 * 193 * TODO: consider publishing by moving into MediaStore. 194 */ 195 private final static String EXTRA_QUICK_CAPTURE = 196 "android.intent.extra.quickCapture"; 197 198 private boolean mPreviewing; 199 private boolean mPausing; 200 private boolean mFirstTimeInitialized; 201 private boolean mIsImageCaptureIntent; 202 private boolean mRecordLocation; 203 204 private static final int FOCUS_NOT_STARTED = 0; 205 private static final int FOCUSING = 1; 206 private static final int FOCUSING_SNAP_ON_FINISH = 2; 207 private static final int FOCUS_SUCCESS = 3; 208 private static final int FOCUS_FAIL = 4; 209 private int mFocusState = FOCUS_NOT_STARTED; 210 211 private ContentResolver mContentResolver; 212 private boolean mDidRegister = false; 213 214 private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); 215 216 private LocationManager mLocationManager = null; 217 218 private final ShutterCallback mShutterCallback = new ShutterCallback(); 219 private final PostViewPictureCallback mPostViewPictureCallback = 220 new PostViewPictureCallback(); 221 private final RawPictureCallback mRawPictureCallback = 222 new RawPictureCallback(); 223 private final AutoFocusCallback mAutoFocusCallback = 224 new AutoFocusCallback(); 225 private final ZoomListener mZoomListener = new ZoomListener(); 226 // Use the ErrorCallback to capture the crash count 227 // on the mediaserver 228 private final ErrorCallback mErrorCallback = new ErrorCallback(); 229 230 private long mFocusStartTime; 231 private long mFocusCallbackTime; 232 private long mCaptureStartTime; 233 private long mShutterCallbackTime; 234 private long mPostViewPictureCallbackTime; 235 private long mRawPictureCallbackTime; 236 private long mJpegPictureCallbackTime; 237 private int mPicturesRemaining; 238 239 // These latency time are for the CameraLatency test. 240 public long mAutoFocusTime; 241 public long mShutterLag; 242 public long mShutterToPictureDisplayedTime; 243 public long mPictureDisplayedToJpegCallbackTime; 244 public long mJpegCallbackFinishTime; 245 246 // Add for test 247 public static boolean mMediaServerDied = false; 248 249 // Focus mode. Options are pref_camera_focusmode_entryvalues. 250 private String mFocusMode; 251 private String mSceneMode; 252 253 private final Handler mHandler = new MainHandler(); 254 private CameraHeadUpDisplay mHeadUpDisplay; 255 private ControlPanel mControlPanel; 256 private PreferenceGroup mPreferenceGroup; 257 258 // multiple cameras support 259 private int mNumberOfCameras; 260 private int mCameraId; 261 262 private boolean mQuickCapture; 263 264 /** 265 * This Handler is used to post message back onto the main thread of the 266 * application 267 */ 268 private class MainHandler extends Handler { 269 @Override 270 public void handleMessage(Message msg) { 271 switch (msg.what) { 272 case RESTART_PREVIEW: { 273 restartPreview(); 274 if (mJpegPictureCallbackTime != 0) { 275 long now = System.currentTimeMillis(); 276 mJpegCallbackFinishTime = now - mJpegPictureCallbackTime; 277 Log.v(TAG, "mJpegCallbackFinishTime = " 278 + mJpegCallbackFinishTime + "ms"); 279 mJpegPictureCallbackTime = 0; 280 } 281 break; 282 } 283 284 case CLEAR_SCREEN_DELAY: { 285 getWindow().clearFlags( 286 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 287 break; 288 } 289 290 case FIRST_TIME_INIT: { 291 initializeFirstTime(); 292 break; 293 } 294 295 case SET_CAMERA_PARAMETERS_WHEN_IDLE: { 296 setCameraParametersWhenIdle(0); 297 break; 298 } 299 } 300 } 301 } 302 303 private void resetExposureCompensation() { 304 String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE, 305 CameraSettings.EXPOSURE_DEFAULT_VALUE); 306 if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) { 307 Editor editor = mPreferences.edit(); 308 editor.putString(CameraSettings.KEY_EXPOSURE, "0"); 309 editor.apply(); 310 if (mHeadUpDisplay != null) { 311 mHeadUpDisplay.reloadPreferences(); 312 } 313 } 314 } 315 316 private void keepMediaProviderInstance() { 317 // We want to keep a reference to MediaProvider in camera's lifecycle. 318 // TODO: Utilize mMediaProviderClient instance to replace 319 // ContentResolver calls. 320 if (mMediaProviderClient == null) { 321 mMediaProviderClient = getContentResolver() 322 .acquireContentProviderClient(MediaStore.AUTHORITY); 323 } 324 } 325 326 // Snapshots can only be taken after this is called. It should be called 327 // once only. We could have done these things in onCreate() but we want to 328 // make preview screen appear as soon as possible. 329 private void initializeFirstTime() { 330 if (mFirstTimeInitialized) return; 331 332 // Create orientation listenter. This should be done first because it 333 // takes some time to get first orientation. 334 mOrientationListener = new MyOrientationEventListener(Camera.this); 335 mOrientationListener.enable(); 336 337 // Initialize location sevice. 338 mLocationManager = (LocationManager) 339 getSystemService(Context.LOCATION_SERVICE); 340 mRecordLocation = RecordLocationPreference.get( 341 mPreferences, getContentResolver()); 342 if (mRecordLocation) startReceivingLocationUpdates(); 343 344 keepMediaProviderInstance(); 345 checkStorage(); 346 347 // Initialize last picture button. 348 mContentResolver = getContentResolver(); 349 if (!mIsImageCaptureIntent) { 350 findViewById(R.id.camera_switch).setOnClickListener(this); 351 initThumbnailButton(); 352 initThumbnailList(); 353 } 354 355 // Initialize shutter button. 356 mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); 357 mShutterButton.setOnShutterButtonListener(this); 358 mShutterButton.setVisibility(View.VISIBLE); 359 360 mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle); 361 updateFocusIndicator(); 362 363 initializeScreenBrightness(); 364 installIntentFilter(); 365 initializeFocusTone(); 366 initializeZoom(); 367 mHeadUpDisplay = new CameraHeadUpDisplay(this); 368 mHeadUpDisplay.setListener(new MyHeadUpDisplayListener()); 369 initializeHeadUpDisplay(); 370 mFirstTimeInitialized = true; 371 changeHeadUpDisplayState(); 372 addIdleHandler(); 373 } 374 375 private void addIdleHandler() { 376 MessageQueue queue = Looper.myQueue(); 377 queue.addIdleHandler(new MessageQueue.IdleHandler() { 378 public boolean queueIdle() { 379 ImageManager.ensureOSXCompatibleFolder(); 380 return false; 381 } 382 }); 383 } 384 385 private void initThumbnailButton() { 386 mThumbnailButton = 387 (RotateImageView) findViewById(R.id.review_thumbnail); 388 if (mThumbnailButton != null) { 389 mThumbnailButton.setOnClickListener(this); 390 mThumbnailButton.loadData(ImageManager.getLastImageThumbPath()); 391 updateThumbnailButton(); 392 } 393 } 394 395 private void updateThumbnailButton() { 396 if (mThumbnailButton == null) return; 397 // Update last image if URI is invalid and the storage is ready. 398 if (!mThumbnailButton.isUriValid() && mPicturesRemaining >= 0) { 399 IImageList list = ImageManager.makeImageList( 400 mContentResolver, 401 dataLocation(), 402 ImageManager.INCLUDE_IMAGES, 403 ImageManager.SORT_ASCENDING, 404 ImageManager.CAMERA_IMAGE_BUCKET_ID); 405 int count = list.getCount(); 406 if (count > 0) { 407 IImage image = list.getImageAt(count - 1); 408 Uri uri = image.fullSizeImageUri(); 409 mThumbnailButton.setData(uri, image.miniThumbBitmap()); 410 } else { 411 mThumbnailButton.setData(null, null); 412 } 413 list.close(); 414 } 415 } 416 417 private void setLastPictureThumb(byte[] data, int degree, Uri uri) { 418 if (mThumbnailButton == null) return; 419 BitmapFactory.Options options = new BitmapFactory.Options(); 420 options.inSampleSize = 16; 421 Bitmap lastPictureThumb = 422 BitmapFactory.decodeByteArray(data, 0, data.length, options); 423 lastPictureThumb = Util.rotate(lastPictureThumb, degree); 424 mThumbnailButton.setData(uri, lastPictureThumb); 425 } 426 427 private void initThumbnailList() { 428 mThumbnailList = (ListView) findViewById(R.id.thumbnail_list); 429 if (mThumbnailList == null) return; 430 431 int width = mThumbnailList.getWidth(); 432 int height = mThumbnailList.getHeight(); 433 434 // Add gallery button to header view. 435 if (mThumbnailList.getHeaderViewsCount() == 0) { 436 LayoutInflater inflater = getLayoutInflater(); 437 Button b = new Button(this); 438 ListView.LayoutParams params = new ListView.LayoutParams(width, width); 439 b.setId(R.id.btn_gallery); 440 b.setLayoutParams(params); 441 b.setOnClickListener(this); 442 b.setBackgroundResource(R.drawable.ic_menu_gallery); 443 mThumbnailList.addHeaderView(b); 444 } 445 446 // Set data adapter. 447 int thumbnailCount = (height + mThumbnailList.getDividerHeight()) 448 / (width + mThumbnailList.getDividerHeight()) - 1; 449 Cursor cursor = getThumbnailsCursor(thumbnailCount); 450 mThumbnailAdapter = new ThumbnailAdapter( 451 getApplicationContext(), R.layout.thumbnail_item, cursor, true); 452 mThumbnailList.setAdapter(mThumbnailAdapter); 453 mThumbnailList.setOnItemClickListener(mThumbnailItemClickListener); 454 } 455 456 private void updateThumbnailList() { 457 if (mThumbnailList == null) return; 458 mThumbnailAdapter.getCursor().requery(); 459 mThumbnailAdapter.notifyDataSetChanged(); 460 } 461 462 private Cursor getThumbnailsCursor(int thumbnailCount) { 463 Log.v(TAG, "thumbnailCount=" + thumbnailCount); 464 String[] projections = { MediaStore.Images.Thumbnails._ID }; 465 Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI 466 .buildUpon() 467 .appendQueryParameter("limit", String.valueOf(thumbnailCount)) 468 .build(); 469 // TODO: managedQuery is deprecated. 470 return managedQuery(uri, projections, 471 Media.MIME_TYPE + " = 'image/jpeg' AND " + Media.BUCKET_ID + " = ?", 472 new String[] {ImageManager.CAMERA_IMAGE_BUCKET_ID}, 473 ImageColumns._ID + " DESC"); 474 } 475 476 // If the activity is paused and resumed, this method will be called in 477 // onResume. 478 private void initializeSecondTime() { 479 // Start orientation listener as soon as possible because it takes 480 // some time to get first orientation. 481 mOrientationListener.enable(); 482 483 // Start location update if needed. 484 mRecordLocation = RecordLocationPreference.get( 485 mPreferences, getContentResolver()); 486 if (mRecordLocation) startReceivingLocationUpdates(); 487 488 installIntentFilter(); 489 initializeFocusTone(); 490 initializeZoom(); 491 changeHeadUpDisplayState(); 492 493 keepMediaProviderInstance(); 494 checkStorage(); 495 496 if (!mIsImageCaptureIntent) { 497 updateThumbnailButton(); 498 } 499 } 500 501 private void initializeZoom() { 502 if (!mParameters.isZoomSupported()) return; 503 504 mZoomMax = mParameters.getMaxZoom(); 505 mSmoothZoomSupported = mParameters.isSmoothZoomSupported(); 506 mGestureDetector = new GestureDetector(this, new ZoomGestureListener()); 507 if (mZoomPicker != null) { 508 mZoomPicker.setZoomRatios(getZoomRatios()); 509 mZoomPicker.setOnZoomChangeListener( 510 new ZoomPicker.OnZoomChangedListener() { 511 public void onZoomChanged(int index) { 512 onZoomValueChanged(index); 513 } 514 }); 515 } 516 517 mCameraDevice.setZoomChangeListener(mZoomListener); 518 } 519 520 private void onZoomValueChanged(int index) { 521 if (mSmoothZoomSupported) { 522 if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) { 523 mTargetZoomValue = index; 524 if (mZoomState == ZOOM_START) { 525 mZoomState = ZOOM_STOPPING; 526 mCameraDevice.stopSmoothZoom(); 527 } 528 } else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) { 529 mTargetZoomValue = index; 530 mCameraDevice.startSmoothZoom(index); 531 mZoomState = ZOOM_START; 532 } 533 } else { 534 mZoomValue = index; 535 setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM); 536 } 537 } 538 539 private float[] getZoomRatios() { 540 if(!mParameters.isZoomSupported()) return null; 541 List<Integer> zoomRatios = mParameters.getZoomRatios(); 542 float result[] = new float[zoomRatios.size()]; 543 for (int i = 0, n = result.length; i < n; ++i) { 544 result[i] = (float) zoomRatios.get(i) / 100f; 545 } 546 return result; 547 } 548 549 private class ZoomGestureListener extends 550 GestureDetector.SimpleOnGestureListener { 551 552 @Override 553 public boolean onDoubleTap(MotionEvent e) { 554 // Perform zoom only when preview is started and snapshot is not in 555 // progress. 556 if (mPausing || !isCameraIdle() || !mPreviewing 557 || mZoomState != ZOOM_STOPPED) { 558 return false; 559 } 560 561 int x = Math.round(e.getX()); 562 int y = Math.round(e.getY()); 563 if (x < mSurfaceView.getLeft() || x > mSurfaceView.getRight() 564 || y < mSurfaceView.getTop() || y > mSurfaceView.getBottom()) { 565 return false; 566 } 567 568 if (mZoomValue < mZoomMax) { 569 // Zoom in to the maximum. 570 mZoomValue = mZoomMax; 571 } else { 572 mZoomValue = 0; 573 } 574 575 setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM); 576 577 if (mZoomPicker != null) { 578 mZoomPicker.setZoomIndex(mZoomValue); 579 } else { 580 mHeadUpDisplay.setZoomIndex(mZoomValue); 581 } 582 return true; 583 } 584 } 585 586 @Override 587 public boolean dispatchTouchEvent(MotionEvent m) { 588 if (!super.dispatchTouchEvent(m) && mGestureDetector != null) { 589 return mGestureDetector.onTouchEvent(m); 590 } 591 return true; 592 } 593 594 LocationListener [] mLocationListeners = new LocationListener[] { 595 new LocationListener(LocationManager.GPS_PROVIDER), 596 new LocationListener(LocationManager.NETWORK_PROVIDER) 597 }; 598 599 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 600 @Override 601 public void onReceive(Context context, Intent intent) { 602 String action = intent.getAction(); 603 if (action.equals(Intent.ACTION_MEDIA_MOUNTED) 604 || action.equals(Intent.ACTION_MEDIA_UNMOUNTED) 605 || action.equals(Intent.ACTION_MEDIA_CHECKING)) { 606 checkStorage(); 607 } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { 608 checkStorage(); 609 if (!mIsImageCaptureIntent) { 610 updateThumbnailButton(); 611 updateThumbnailList(); 612 } 613 } 614 } 615 }; 616 617 private class LocationListener 618 implements android.location.LocationListener { 619 Location mLastLocation; 620 boolean mValid = false; 621 String mProvider; 622 623 public LocationListener(String provider) { 624 mProvider = provider; 625 mLastLocation = new Location(mProvider); 626 } 627 628 public void onLocationChanged(Location newLocation) { 629 if (newLocation.getLatitude() == 0.0 630 && newLocation.getLongitude() == 0.0) { 631 // Hack to filter out 0.0,0.0 locations 632 return; 633 } 634 // If GPS is available before start camera, we won't get status 635 // update so update GPS indicator when we receive data. 636 if (mRecordLocation 637 && LocationManager.GPS_PROVIDER.equals(mProvider)) { 638 if (mHeadUpDisplay != null) { 639 mHeadUpDisplay.setGpsHasSignal(true); 640 } 641 } 642 mLastLocation.set(newLocation); 643 mValid = true; 644 } 645 646 public void onProviderEnabled(String provider) { 647 } 648 649 public void onProviderDisabled(String provider) { 650 mValid = false; 651 } 652 653 public void onStatusChanged( 654 String provider, int status, Bundle extras) { 655 switch(status) { 656 case LocationProvider.OUT_OF_SERVICE: 657 case LocationProvider.TEMPORARILY_UNAVAILABLE: { 658 mValid = false; 659 if (mRecordLocation && 660 LocationManager.GPS_PROVIDER.equals(provider)) { 661 if (mHeadUpDisplay != null) { 662 mHeadUpDisplay.setGpsHasSignal(false); 663 } 664 } 665 break; 666 } 667 } 668 } 669 670 public Location current() { 671 return mValid ? mLastLocation : null; 672 } 673 } 674 675 private final class ShutterCallback 676 implements android.hardware.Camera.ShutterCallback { 677 public void onShutter() { 678 mShutterCallbackTime = System.currentTimeMillis(); 679 mShutterLag = mShutterCallbackTime - mCaptureStartTime; 680 Log.v(TAG, "mShutterLag = " + mShutterLag + "ms"); 681 clearFocusState(); 682 } 683 } 684 685 private final class PostViewPictureCallback implements PictureCallback { 686 public void onPictureTaken( 687 byte [] data, android.hardware.Camera camera) { 688 mPostViewPictureCallbackTime = System.currentTimeMillis(); 689 Log.v(TAG, "mShutterToPostViewCallbackTime = " 690 + (mPostViewPictureCallbackTime - mShutterCallbackTime) 691 + "ms"); 692 } 693 } 694 695 private final class RawPictureCallback implements PictureCallback { 696 public void onPictureTaken( 697 byte [] rawData, android.hardware.Camera camera) { 698 mRawPictureCallbackTime = System.currentTimeMillis(); 699 Log.v(TAG, "mShutterToRawCallbackTime = " 700 + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms"); 701 } 702 } 703 704 private final class JpegPictureCallback implements PictureCallback { 705 Location mLocation; 706 707 public JpegPictureCallback(Location loc) { 708 mLocation = loc; 709 } 710 711 public void onPictureTaken( 712 final byte [] jpegData, final android.hardware.Camera camera) { 713 if (mPausing) { 714 return; 715 } 716 717 mJpegPictureCallbackTime = System.currentTimeMillis(); 718 // If postview callback has arrived, the captured image is displayed 719 // in postview callback. If not, the captured image is displayed in 720 // raw picture callback. 721 if (mPostViewPictureCallbackTime != 0) { 722 mShutterToPictureDisplayedTime = 723 mPostViewPictureCallbackTime - mShutterCallbackTime; 724 mPictureDisplayedToJpegCallbackTime = 725 mJpegPictureCallbackTime - mPostViewPictureCallbackTime; 726 } else { 727 mShutterToPictureDisplayedTime = 728 mRawPictureCallbackTime - mShutterCallbackTime; 729 mPictureDisplayedToJpegCallbackTime = 730 mJpegPictureCallbackTime - mRawPictureCallbackTime; 731 } 732 Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = " 733 + mPictureDisplayedToJpegCallbackTime + "ms"); 734 mHeadUpDisplay.setEnabled(true); 735 736 if (!mIsImageCaptureIntent) { 737 // We want to show the taken picture for a while, so we wait 738 // for at least 1.2 second before restarting the preview. 739 long delay = 1200 - mPictureDisplayedToJpegCallbackTime; 740 if (delay < 0) { 741 restartPreview(); 742 } else { 743 mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay); 744 } 745 } 746 mImageCapture.storeImage(jpegData, camera, mLocation); 747 748 // Calculate this in advance of each shot so we don't add to shutter 749 // latency. It's true that someone else could write to the SD card in 750 // the mean time and fill it, but that could have happened between the 751 // shutter press and saving the JPEG too. 752 calculatePicturesRemaining(); 753 754 if (mPicturesRemaining < 1) { 755 updateStorageHint(mPicturesRemaining); 756 } 757 758 if (!mHandler.hasMessages(RESTART_PREVIEW)) { 759 long now = System.currentTimeMillis(); 760 mJpegCallbackFinishTime = now - mJpegPictureCallbackTime; 761 Log.v(TAG, "mJpegCallbackFinishTime = " 762 + mJpegCallbackFinishTime + "ms"); 763 mJpegPictureCallbackTime = 0; 764 } 765 } 766 } 767 768 private final class AutoFocusCallback 769 implements android.hardware.Camera.AutoFocusCallback { 770 public void onAutoFocus( 771 boolean focused, android.hardware.Camera camera) { 772 mFocusCallbackTime = System.currentTimeMillis(); 773 mAutoFocusTime = mFocusCallbackTime - mFocusStartTime; 774 Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms"); 775 if (mFocusState == FOCUSING_SNAP_ON_FINISH) { 776 // Take the picture no matter focus succeeds or fails. No need 777 // to play the AF sound if we're about to play the shutter 778 // sound. 779 if (focused) { 780 mFocusState = FOCUS_SUCCESS; 781 } else { 782 mFocusState = FOCUS_FAIL; 783 } 784 mImageCapture.onSnap(); 785 } else if (mFocusState == FOCUSING) { 786 // User is half-pressing the focus key. Play the focus tone. 787 // Do not take the picture now. 788 ToneGenerator tg = mFocusToneGenerator; 789 if (tg != null) { 790 tg.startTone(ToneGenerator.TONE_PROP_BEEP2); 791 } 792 if (focused) { 793 mFocusState = FOCUS_SUCCESS; 794 } else { 795 mFocusState = FOCUS_FAIL; 796 } 797 } else if (mFocusState == FOCUS_NOT_STARTED) { 798 // User has released the focus key before focus completes. 799 // Do nothing. 800 } 801 updateFocusIndicator(); 802 } 803 } 804 805 private static final class ErrorCallback 806 implements android.hardware.Camera.ErrorCallback { 807 public void onError(int error, android.hardware.Camera camera) { 808 if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) { 809 mMediaServerDied = true; 810 Log.v(TAG, "media server died"); 811 } 812 } 813 } 814 815 private final class ZoomListener 816 implements android.hardware.Camera.OnZoomChangeListener { 817 public void onZoomChange( 818 int value, boolean stopped, android.hardware.Camera camera) { 819 Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped); 820 mZoomValue = value; 821 // Keep mParameters up to date. We do not getParameter again in 822 // takePicture. If we do not do this, wrong zoom value will be set. 823 mParameters.setZoom(value); 824 // We only care if the zoom is stopped. mZooming is set to true when 825 // we start smooth zoom. 826 if (stopped && mZoomState != ZOOM_STOPPED) { 827 if (value != mTargetZoomValue) { 828 mCameraDevice.startSmoothZoom(mTargetZoomValue); 829 mZoomState = ZOOM_START; 830 } else { 831 mZoomState = ZOOM_STOPPED; 832 } 833 } 834 } 835 } 836 837 private class ImageCapture { 838 839 private Uri mLastContentUri; 840 841 byte[] mCaptureOnlyData; 842 843 // Returns the rotation degree in the jpeg header. 844 private int storeImage(byte[] data, Location loc) { 845 try { 846 long dateTaken = System.currentTimeMillis(); 847 String title = createName(dateTaken); 848 String filename = title + ".jpg"; 849 int[] degree = new int[1]; 850 mLastContentUri = ImageManager.addImage( 851 mContentResolver, 852 title, 853 dateTaken, 854 loc, // location from gps/network 855 ImageManager.CAMERA_IMAGE_BUCKET_NAME, filename, 856 null, data, 857 degree); 858 return degree[0]; 859 } catch (Exception ex) { 860 Log.e(TAG, "Exception while compressing image.", ex); 861 return 0; 862 } 863 } 864 865 public void storeImage(final byte[] data, 866 android.hardware.Camera camera, Location loc) { 867 if (!mIsImageCaptureIntent) { 868 int degree = storeImage(data, loc); 869 sendBroadcast(new Intent( 870 "com.android.camera.NEW_PICTURE", mLastContentUri)); 871 setLastPictureThumb(data, degree, 872 mImageCapture.getLastCaptureUri()); 873 updateThumbnailList(); 874 } else { 875 mCaptureOnlyData = data; 876 if (!mQuickCapture) { 877 showPostCaptureAlert(); 878 } else { 879 doAttach(); 880 } 881 } 882 } 883 884 /** 885 * Initiate the capture of an image. 886 */ 887 public void initiate() { 888 if (mCameraDevice == null) { 889 return; 890 } 891 892 capture(); 893 } 894 895 public Uri getLastCaptureUri() { 896 return mLastContentUri; 897 } 898 899 public byte[] getLastCaptureData() { 900 return mCaptureOnlyData; 901 } 902 903 private void capture() { 904 mCaptureOnlyData = null; 905 906 // See android.hardware.Camera.Parameters.setRotation for 907 // documentation. 908 int rotation = 0; 909 if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) { 910 CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; 911 if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 912 rotation = (info.orientation - mOrientation + 360) % 360; 913 } else { // back-facing camera 914 rotation = (info.orientation + mOrientation) % 360; 915 } 916 } 917 mParameters.setRotation(rotation); 918 919 // Clear previous GPS location from the parameters. 920 mParameters.removeGpsData(); 921 922 // We always encode GpsTimeStamp 923 mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000); 924 925 // Set GPS location. 926 Location loc = mRecordLocation ? getCurrentLocation() : null; 927 if (loc != null) { 928 double lat = loc.getLatitude(); 929 double lon = loc.getLongitude(); 930 boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); 931 932 if (hasLatLon) { 933 mParameters.setGpsLatitude(lat); 934 mParameters.setGpsLongitude(lon); 935 mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase()); 936 if (loc.hasAltitude()) { 937 mParameters.setGpsAltitude(loc.getAltitude()); 938 } else { 939 // for NETWORK_PROVIDER location provider, we may have 940 // no altitude information, but the driver needs it, so 941 // we fake one. 942 mParameters.setGpsAltitude(0); 943 } 944 if (loc.getTime() != 0) { 945 // Location.getTime() is UTC in milliseconds. 946 // gps-timestamp is UTC in seconds. 947 long utcTimeSeconds = loc.getTime() / 1000; 948 mParameters.setGpsTimestamp(utcTimeSeconds); 949 } 950 } else { 951 loc = null; 952 } 953 } 954 955 mCameraDevice.setParameters(mParameters); 956 957 mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, 958 mPostViewPictureCallback, new JpegPictureCallback(loc)); 959 mPreviewing = false; 960 } 961 962 public void onSnap() { 963 // If we are already in the middle of taking a snapshot then ignore. 964 if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) { 965 return; 966 } 967 mCaptureStartTime = System.currentTimeMillis(); 968 mPostViewPictureCallbackTime = 0; 969 mHeadUpDisplay.setEnabled(false); 970 mStatus = SNAPSHOT_IN_PROGRESS; 971 972 mImageCapture.initiate(); 973 } 974 975 private void clearLastData() { 976 mCaptureOnlyData = null; 977 } 978 } 979 980 private boolean saveDataToFile(String filePath, byte[] data) { 981 FileOutputStream f = null; 982 try { 983 f = new FileOutputStream(filePath); 984 f.write(data); 985 } catch (IOException e) { 986 return false; 987 } finally { 988 MenuHelper.closeSilently(f); 989 } 990 return true; 991 } 992 993 private String createName(long dateTaken) { 994 Date date = new Date(dateTaken); 995 SimpleDateFormat dateFormat = new SimpleDateFormat( 996 getString(R.string.image_file_name_format)); 997 998 return dateFormat.format(date); 999 } 1000 1001 @Override 1002 public void onCreate(Bundle icicle) { 1003 super.onCreate(icicle); 1004 1005 setContentView(R.layout.camera); 1006 mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview); 1007 1008 mPreferences = new ComboPreferences(this); 1009 CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal()); 1010 mCameraId = CameraSettings.readPreferredCameraId(mPreferences); 1011 mPreferences.setLocalId(this, mCameraId); 1012 CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); 1013 1014 mNumberOfCameras = CameraHolder.instance().getNumberOfCameras(); 1015 mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); 1016 1017 // we need to reset exposure for the preview 1018 resetExposureCompensation(); 1019 /* 1020 * To reduce startup time, we start the preview in another thread. 1021 * We make sure the preview is started at the end of onCreate. 1022 */ 1023 Thread startPreviewThread = new Thread(new Runnable() { 1024 public void run() { 1025 try { 1026 mStartPreviewFail = false; 1027 startPreview(); 1028 } catch (CameraHardwareException e) { 1029 // In eng build, we throw the exception so that test tool 1030 // can detect it and report it 1031 if ("eng".equals(Build.TYPE)) { 1032 throw new RuntimeException(e); 1033 } 1034 mStartPreviewFail = true; 1035 } 1036 } 1037 }); 1038 startPreviewThread.start(); 1039 1040 // don't set mSurfaceHolder here. We have it set ONLY within 1041 // surfaceChanged / surfaceDestroyed, other parts of the code 1042 // assume that when it is set, the surface is also set. 1043 SurfaceHolder holder = mSurfaceView.getHolder(); 1044 holder.addCallback(this); 1045 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 1046 1047 mIsImageCaptureIntent = isImageCaptureIntent(); 1048 if (mIsImageCaptureIntent) { 1049 setupCaptureParams(); 1050 } 1051 1052 LayoutInflater inflater = getLayoutInflater(); 1053 1054 ViewGroup rootView = (ViewGroup) findViewById(R.id.camera); 1055 if (mIsImageCaptureIntent) { 1056 View controlBar = inflater.inflate( 1057 R.layout.attach_camera_control, rootView); 1058 controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this); 1059 controlBar.findViewById(R.id.btn_retake).setOnClickListener(this); 1060 controlBar.findViewById(R.id.btn_done).setOnClickListener(this); 1061 } else { 1062 inflater.inflate(R.layout.camera_control, rootView); 1063 mSwitcher = ((Switcher) findViewById(R.id.camera_switch)); 1064 mSwitcher.setOnSwitchListener(this); 1065 mSwitcher.addTouchView(findViewById(R.id.camera_switch_set)); 1066 } 1067 1068 // Show zoom picker. 1069 ViewStub zoomStub = (ViewStub) findViewById(R.id.zoom_stub); 1070 if (zoomStub != null) mZoomPicker = (ZoomPicker) zoomStub.inflate(); 1071 1072 // Make sure preview is started. 1073 try { 1074 startPreviewThread.join(); 1075 if (mStartPreviewFail) { 1076 showCameraErrorAndFinish(); 1077 return; 1078 } 1079 } catch (InterruptedException ex) { 1080 // ignore 1081 } 1082 1083 initializeControlPanel(); 1084 } 1085 1086 private void changeHeadUpDisplayState() { 1087 // If the camera resumes behind the lock screen, the orientation 1088 // will be portrait. That causes OOM when we try to allocation GPU 1089 // memory for the GLSurfaceView again when the orientation changes. So, 1090 // we delayed initialization of HeadUpDisplay until the orientation 1091 // becomes landscape. 1092 Configuration config = getResources().getConfiguration(); 1093 if (config.orientation == Configuration.ORIENTATION_LANDSCAPE 1094 && !mPausing && mFirstTimeInitialized) { 1095 if (mGLRootView == null) attachHeadUpDisplay(); 1096 } else if (mGLRootView != null) { 1097 detachHeadUpDisplay(); 1098 } 1099 } 1100 1101 private void overrideHudSettings(final String flashMode, 1102 final String whiteBalance, final String focusMode) { 1103 mHeadUpDisplay.overrideSettings( 1104 CameraSettings.KEY_FLASH_MODE, flashMode, 1105 CameraSettings.KEY_WHITE_BALANCE, whiteBalance, 1106 CameraSettings.KEY_FOCUS_MODE, focusMode); 1107 } 1108 1109 private void updateSceneModeInHud() { 1110 // If scene mode is set, we cannot set flash mode, white balance, and 1111 // focus mode, instead, we read it from driver 1112 if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 1113 overrideHudSettings(mParameters.getFlashMode(), 1114 mParameters.getWhiteBalance(), mParameters.getFocusMode()); 1115 } else { 1116 overrideHudSettings(null, null, null); 1117 } 1118 } 1119 1120 private void initializeControlPanel() { 1121 String[] keys = new String[]{CameraSettings.KEY_FLASH_MODE, 1122 CameraSettings.KEY_WHITE_BALANCE, 1123 CameraSettings.KEY_RECORD_LOCATION, 1124 CameraSettings.KEY_CAMERA_ID}; 1125 mControlPanel = (ControlPanel) findViewById(R.id.control_panel); 1126 if (mControlPanel != null) { 1127 CameraSettings settings = new CameraSettings(this, mInitialParams, 1128 mCameraId, CameraHolder.instance().getCameraInfo()); 1129 mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences); 1130 mControlPanel.initialize(this, mPreferenceGroup, keys); 1131 mControlPanel.setListener(new MyControlPanelListener()); 1132 } 1133 } 1134 1135 private void initializeHeadUpDisplay() { 1136 CameraSettings settings = new CameraSettings(this, mInitialParams, 1137 mCameraId, CameraHolder.instance().getCameraInfo()); 1138 // If we have zoom picker, do not show zoom control on head-up display. 1139 float[] zoomRatios = null; 1140 if (mZoomPicker == null) zoomRatios = getZoomRatios(); 1141 mHeadUpDisplay.initialize(this, 1142 settings.getPreferenceGroup(R.xml.camera_preferences), 1143 zoomRatios, mOrientationCompensation); 1144 if (mZoomPicker == null && mParameters.isZoomSupported()) { 1145 mHeadUpDisplay.setZoomListener(new ZoomControllerListener() { 1146 public void onZoomChanged( 1147 int index, float ratio, boolean isMoving) { 1148 onZoomValueChanged(index); 1149 } 1150 }); 1151 } 1152 updateSceneModeInHud(); 1153 } 1154 1155 private void attachHeadUpDisplay() { 1156 mHeadUpDisplay.setOrientation(mOrientationCompensation); 1157 if (mZoomPicker == null && mParameters.isZoomSupported()) { 1158 mHeadUpDisplay.setZoomIndex(mZoomValue); 1159 } 1160 FrameLayout frame = (FrameLayout) findViewById(R.id.frame); 1161 mGLRootView = new GLRootView(this); 1162 mGLRootView.setContentPane(mHeadUpDisplay); 1163 frame.addView(mGLRootView); 1164 } 1165 1166 private void detachHeadUpDisplay() { 1167 mHeadUpDisplay.setGpsHasSignal(false); 1168 mHeadUpDisplay.collapse(); 1169 ((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView); 1170 mGLRootView = null; 1171 } 1172 1173 public static int roundOrientation(int orientation) { 1174 return ((orientation + 45) / 90 * 90) % 360; 1175 } 1176 1177 private class MyOrientationEventListener 1178 extends OrientationEventListener { 1179 public MyOrientationEventListener(Context context) { 1180 super(context); 1181 } 1182 1183 @Override 1184 public void onOrientationChanged(int orientation) { 1185 // We keep the last known orientation. So if the user first orient 1186 // the camera then point the camera to floor or sky, we still have 1187 // the correct orientation. 1188 if (orientation == ORIENTATION_UNKNOWN) return; 1189 orientation = roundOrientation(orientation); 1190 if (orientation != mOrientation) { 1191 mOrientation = orientation; 1192 mOrientationCompensation = orientation 1193 + Util.getDisplayRotation(Camera.this); 1194 1195 if (!mIsImageCaptureIntent) { 1196 setOrientationIndicator(mOrientationCompensation); 1197 } 1198 mHeadUpDisplay.setOrientation(mOrientationCompensation); 1199 } 1200 } 1201 } 1202 1203 private void setOrientationIndicator(int degree) { 1204 RotateImageView thumbnail = (RotateImageView) findViewById( 1205 R.id.review_thumbnail); 1206 if (thumbnail != null) thumbnail.setDegree(degree); 1207 1208 ((RotateImageView) findViewById( 1209 R.id.camera_switch_icon)).setDegree(degree); 1210 ((RotateImageView) findViewById( 1211 R.id.video_switch_icon)).setDegree(degree); 1212 } 1213 1214 @Override 1215 public void onStart() { 1216 super.onStart(); 1217 if (!mIsImageCaptureIntent) { 1218 mSwitcher.setSwitch(SWITCH_CAMERA); 1219 } 1220 } 1221 1222 @Override 1223 public void onStop() { 1224 super.onStop(); 1225 if (mMediaProviderClient != null) { 1226 mMediaProviderClient.release(); 1227 mMediaProviderClient = null; 1228 } 1229 } 1230 1231 private void checkStorage() { 1232 calculatePicturesRemaining(); 1233 updateStorageHint(mPicturesRemaining); 1234 } 1235 1236 public void onClick(View v) { 1237 switch (v.getId()) { 1238 case R.id.btn_retake: 1239 hidePostCaptureAlert(); 1240 restartPreview(); 1241 break; 1242 case R.id.review_thumbnail: 1243 if (isCameraIdle()) { 1244 viewImage(mThumbnailButton); 1245 } 1246 break; 1247 case R.id.btn_done: 1248 doAttach(); 1249 break; 1250 case R.id.btn_cancel: 1251 doCancel(); 1252 break; 1253 case R.id.btn_gallery: 1254 gotoGallery(); 1255 break; 1256 } 1257 } 1258 1259 private class ThumbnailItemClickListener implements OnItemClickListener { 1260 public void onItemClick(AdapterView<?> p, View v, int pos, long id) { 1261 viewImage((RotateImageView)v); 1262 } 1263 } 1264 1265 private Bitmap createCaptureBitmap(byte[] data) { 1266 // This is really stupid...we just want to read the orientation in 1267 // the jpeg header. 1268 String filepath = ImageManager.getTempJpegPath(); 1269 int degree = 0; 1270 if (saveDataToFile(filepath, data)) { 1271 degree = ImageManager.getExifOrientation(filepath); 1272 new File(filepath).delete(); 1273 } 1274 1275 // Limit to 50k pixels so we can return it in the intent. 1276 Bitmap bitmap = Util.makeBitmap(data, 50 * 1024); 1277 bitmap = Util.rotate(bitmap, degree); 1278 return bitmap; 1279 } 1280 1281 private void doAttach() { 1282 if (mPausing) { 1283 return; 1284 } 1285 1286 byte[] data = mImageCapture.getLastCaptureData(); 1287 1288 if (mCropValue == null) { 1289 // First handle the no crop case -- just return the value. If the 1290 // caller specifies a "save uri" then write the data to it's 1291 // stream. Otherwise, pass back a scaled down version of the bitmap 1292 // directly in the extras. 1293 if (mSaveUri != null) { 1294 OutputStream outputStream = null; 1295 try { 1296 outputStream = mContentResolver.openOutputStream(mSaveUri); 1297 outputStream.write(data); 1298 outputStream.close(); 1299 1300 setResult(RESULT_OK); 1301 finish(); 1302 } catch (IOException ex) { 1303 // ignore exception 1304 } finally { 1305 Util.closeSilently(outputStream); 1306 } 1307 } else { 1308 Bitmap bitmap = createCaptureBitmap(data); 1309 setResult(RESULT_OK, 1310 new Intent("inline-data").putExtra("data", bitmap)); 1311 finish(); 1312 } 1313 } else { 1314 // Save the image to a temp file and invoke the cropper 1315 Uri tempUri = null; 1316 FileOutputStream tempStream = null; 1317 try { 1318 File path = getFileStreamPath(sTempCropFilename); 1319 path.delete(); 1320 tempStream = openFileOutput(sTempCropFilename, 0); 1321 tempStream.write(data); 1322 tempStream.close(); 1323 tempUri = Uri.fromFile(path); 1324 } catch (FileNotFoundException ex) { 1325 setResult(Activity.RESULT_CANCELED); 1326 finish(); 1327 return; 1328 } catch (IOException ex) { 1329 setResult(Activity.RESULT_CANCELED); 1330 finish(); 1331 return; 1332 } finally { 1333 Util.closeSilently(tempStream); 1334 } 1335 1336 Bundle newExtras = new Bundle(); 1337 if (mCropValue.equals("circle")) { 1338 newExtras.putString("circleCrop", "true"); 1339 } 1340 if (mSaveUri != null) { 1341 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri); 1342 } else { 1343 newExtras.putBoolean("return-data", true); 1344 } 1345 1346 Intent cropIntent = new Intent("com.android.camera.action.CROP"); 1347 1348 cropIntent.setData(tempUri); 1349 cropIntent.putExtras(newExtras); 1350 1351 startActivityForResult(cropIntent, CROP_MSG); 1352 } 1353 } 1354 1355 private void doCancel() { 1356 setResult(RESULT_CANCELED, new Intent()); 1357 finish(); 1358 } 1359 1360 public void onShutterButtonFocus(ShutterButton button, boolean pressed) { 1361 if (mPausing) { 1362 return; 1363 } 1364 switch (button.getId()) { 1365 case R.id.shutter_button: 1366 doFocus(pressed); 1367 break; 1368 } 1369 } 1370 1371 public void onShutterButtonClick(ShutterButton button) { 1372 if (mPausing) { 1373 return; 1374 } 1375 switch (button.getId()) { 1376 case R.id.shutter_button: 1377 doSnap(); 1378 break; 1379 } 1380 } 1381 1382 private OnScreenHint mStorageHint; 1383 1384 private void updateStorageHint(int remaining) { 1385 String noStorageText = null; 1386 1387 if (remaining == MenuHelper.NO_STORAGE_ERROR) { 1388 String state = Environment.getExternalStorageState(); 1389 if (state == Environment.MEDIA_CHECKING) { 1390 noStorageText = getString(R.string.preparing_sd); 1391 } else { 1392 noStorageText = getString(R.string.no_storage); 1393 } 1394 } else if (remaining == MenuHelper.CANNOT_STAT_ERROR) { 1395 noStorageText = getString(R.string.access_sd_fail); 1396 } else if (remaining < 1) { 1397 noStorageText = getString(R.string.not_enough_space); 1398 } 1399 1400 if (noStorageText != null) { 1401 if (mStorageHint == null) { 1402 mStorageHint = OnScreenHint.makeText(this, noStorageText); 1403 } else { 1404 mStorageHint.setText(noStorageText); 1405 } 1406 mStorageHint.show(); 1407 } else if (mStorageHint != null) { 1408 mStorageHint.cancel(); 1409 mStorageHint = null; 1410 } 1411 } 1412 1413 private void installIntentFilter() { 1414 // install an intent filter to receive SD card related events. 1415 IntentFilter intentFilter = 1416 new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); 1417 intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); 1418 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); 1419 intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); 1420 intentFilter.addDataScheme("file"); 1421 registerReceiver(mReceiver, intentFilter); 1422 mDidRegister = true; 1423 } 1424 1425 private void initializeFocusTone() { 1426 // Initialize focus tone generator. 1427 try { 1428 mFocusToneGenerator = new ToneGenerator( 1429 AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); 1430 } catch (Throwable ex) { 1431 Log.w(TAG, "Exception caught while creating tone generator: ", ex); 1432 mFocusToneGenerator = null; 1433 } 1434 } 1435 1436 private void initializeScreenBrightness() { 1437 Window win = getWindow(); 1438 // Overright the brightness settings if it is automatic 1439 int mode = Settings.System.getInt( 1440 getContentResolver(), 1441 Settings.System.SCREEN_BRIGHTNESS_MODE, 1442 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); 1443 if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { 1444 WindowManager.LayoutParams winParams = win.getAttributes(); 1445 winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS; 1446 win.setAttributes(winParams); 1447 } 1448 } 1449 1450 @Override 1451 protected void onResume() { 1452 super.onResume(); 1453 1454 mPausing = false; 1455 mJpegPictureCallbackTime = 0; 1456 mZoomValue = 0; 1457 mImageCapture = new ImageCapture(); 1458 1459 // Start the preview if it is not started. 1460 if (!mPreviewing && !mStartPreviewFail) { 1461 resetExposureCompensation(); 1462 if (!restartPreview()) return; 1463 } 1464 1465 if (mSurfaceHolder != null) { 1466 // If first time initialization is not finished, put it in the 1467 // message queue. 1468 if (!mFirstTimeInitialized) { 1469 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1470 } else { 1471 initializeSecondTime(); 1472 } 1473 } 1474 keepScreenOnAwhile(); 1475 } 1476 1477 @Override 1478 public void onConfigurationChanged(Configuration config) { 1479 super.onConfigurationChanged(config); 1480 changeHeadUpDisplayState(); 1481 } 1482 1483 private static ImageManager.DataLocation dataLocation() { 1484 return ImageManager.DataLocation.EXTERNAL; 1485 } 1486 1487 @Override 1488 protected void onPause() { 1489 mPausing = true; 1490 stopPreview(); 1491 // Close the camera now because other activities may need to use it. 1492 closeCamera(); 1493 resetScreenOn(); 1494 changeHeadUpDisplayState(); 1495 if (mControlPanel != null) mControlPanel.hideSettingPicker(); 1496 1497 if (mFirstTimeInitialized) { 1498 mOrientationListener.disable(); 1499 if (!mIsImageCaptureIntent) { 1500 if (mThumbnailButton != null) { 1501 mThumbnailButton.storeData( 1502 ImageManager.getLastImageThumbPath()); 1503 } 1504 } 1505 hidePostCaptureAlert(); 1506 } 1507 1508 if (mDidRegister) { 1509 unregisterReceiver(mReceiver); 1510 mDidRegister = false; 1511 } 1512 stopReceivingLocationUpdates(); 1513 1514 if (mFocusToneGenerator != null) { 1515 mFocusToneGenerator.release(); 1516 mFocusToneGenerator = null; 1517 } 1518 1519 if (mStorageHint != null) { 1520 mStorageHint.cancel(); 1521 mStorageHint = null; 1522 } 1523 1524 // If we are in an image capture intent and has taken 1525 // a picture, we just clear it in onPause. 1526 mImageCapture.clearLastData(); 1527 mImageCapture = null; 1528 1529 // Remove the messages in the event queue. 1530 mHandler.removeMessages(RESTART_PREVIEW); 1531 mHandler.removeMessages(FIRST_TIME_INIT); 1532 1533 super.onPause(); 1534 } 1535 1536 @Override 1537 protected void onActivityResult( 1538 int requestCode, int resultCode, Intent data) { 1539 switch (requestCode) { 1540 case CROP_MSG: { 1541 Intent intent = new Intent(); 1542 if (data != null) { 1543 Bundle extras = data.getExtras(); 1544 if (extras != null) { 1545 intent.putExtras(extras); 1546 } 1547 } 1548 setResult(resultCode, intent); 1549 finish(); 1550 1551 File path = getFileStreamPath(sTempCropFilename); 1552 path.delete(); 1553 1554 break; 1555 } 1556 } 1557 } 1558 1559 private boolean canTakePicture() { 1560 return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0); 1561 } 1562 1563 private void autoFocus() { 1564 // Initiate autofocus only when preview is started and snapshot is not 1565 // in progress. 1566 if (canTakePicture()) { 1567 mHeadUpDisplay.setEnabled(false); 1568 Log.v(TAG, "Start autofocus."); 1569 mFocusStartTime = System.currentTimeMillis(); 1570 mFocusState = FOCUSING; 1571 updateFocusIndicator(); 1572 mCameraDevice.autoFocus(mAutoFocusCallback); 1573 } 1574 } 1575 1576 private void cancelAutoFocus() { 1577 // User releases half-pressed focus key. 1578 if (mStatus != SNAPSHOT_IN_PROGRESS && (mFocusState == FOCUSING 1579 || mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) { 1580 Log.v(TAG, "Cancel autofocus."); 1581 mHeadUpDisplay.setEnabled(true); 1582 mCameraDevice.cancelAutoFocus(); 1583 } 1584 if (mFocusState != FOCUSING_SNAP_ON_FINISH) { 1585 clearFocusState(); 1586 } 1587 } 1588 1589 private void clearFocusState() { 1590 mFocusState = FOCUS_NOT_STARTED; 1591 updateFocusIndicator(); 1592 } 1593 1594 private void updateFocusIndicator() { 1595 if (mFocusRectangle == null) return; 1596 1597 if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) { 1598 mFocusRectangle.showStart(); 1599 } else if (mFocusState == FOCUS_SUCCESS) { 1600 mFocusRectangle.showSuccess(); 1601 } else if (mFocusState == FOCUS_FAIL) { 1602 mFocusRectangle.showFail(); 1603 } else { 1604 mFocusRectangle.clear(); 1605 } 1606 } 1607 1608 @Override 1609 public void onBackPressed() { 1610 if (!isCameraIdle()) { 1611 // ignore backs while we're taking a picture 1612 return; 1613 } else if (mHeadUpDisplay == null || !mHeadUpDisplay.collapse()) { 1614 super.onBackPressed(); 1615 } 1616 } 1617 1618 @Override 1619 public boolean onKeyDown(int keyCode, KeyEvent event) { 1620 switch (keyCode) { 1621 case KeyEvent.KEYCODE_FOCUS: 1622 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1623 doFocus(true); 1624 } 1625 return true; 1626 case KeyEvent.KEYCODE_CAMERA: 1627 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1628 doSnap(); 1629 } 1630 return true; 1631 case KeyEvent.KEYCODE_DPAD_CENTER: 1632 // If we get a dpad center event without any focused view, move 1633 // the focus to the shutter button and press it. 1634 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1635 // Start auto-focus immediately to reduce shutter lag. After 1636 // the shutter button gets the focus, doFocus() will be 1637 // called again but it is fine. 1638 if (mHeadUpDisplay.collapse()) return true; 1639 if (mControlPanel != null) mControlPanel.hideSettingPicker(); 1640 doFocus(true); 1641 if (mShutterButton.isInTouchMode()) { 1642 mShutterButton.requestFocusFromTouch(); 1643 } else { 1644 mShutterButton.requestFocus(); 1645 } 1646 mShutterButton.setPressed(true); 1647 } 1648 return true; 1649 } 1650 1651 return super.onKeyDown(keyCode, event); 1652 } 1653 1654 @Override 1655 public boolean onKeyUp(int keyCode, KeyEvent event) { 1656 switch (keyCode) { 1657 case KeyEvent.KEYCODE_FOCUS: 1658 if (mFirstTimeInitialized) { 1659 doFocus(false); 1660 } 1661 return true; 1662 } 1663 return super.onKeyUp(keyCode, event); 1664 } 1665 1666 private void doSnap() { 1667 if (mHeadUpDisplay.collapse()) return; 1668 if (mControlPanel != null) mControlPanel.hideSettingPicker(); 1669 1670 Log.v(TAG, "doSnap: mFocusState=" + mFocusState); 1671 // If the user has half-pressed the shutter and focus is completed, we 1672 // can take the photo right away. If the focus mode is infinity, we can 1673 // also take the photo. 1674 if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY) 1675 || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED) 1676 || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF) 1677 || (mFocusState == FOCUS_SUCCESS 1678 || mFocusState == FOCUS_FAIL)) { 1679 mImageCapture.onSnap(); 1680 } else if (mFocusState == FOCUSING) { 1681 // Half pressing the shutter (i.e. the focus button event) will 1682 // already have requested AF for us, so just request capture on 1683 // focus here. 1684 mFocusState = FOCUSING_SNAP_ON_FINISH; 1685 } else if (mFocusState == FOCUS_NOT_STARTED) { 1686 // Focus key down event is dropped for some reasons. Just ignore. 1687 } 1688 } 1689 1690 private void doFocus(boolean pressed) { 1691 // Do the focus if the mode is not infinity. 1692 if (mHeadUpDisplay.collapse()) return; 1693 if (mControlPanel != null) mControlPanel.hideSettingPicker(); 1694 if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY) 1695 || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED) 1696 || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) { 1697 if (pressed) { // Focus key down. 1698 autoFocus(); 1699 } else { // Focus key up. 1700 cancelAutoFocus(); 1701 } 1702 } 1703 } 1704 1705 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1706 // Make sure we have a surface in the holder before proceeding. 1707 if (holder.getSurface() == null) { 1708 Log.d(TAG, "holder.getSurface() == null"); 1709 return; 1710 } 1711 1712 // We need to save the holder for later use, even when the mCameraDevice 1713 // is null. This could happen if onResume() is invoked after this 1714 // function. 1715 mSurfaceHolder = holder; 1716 1717 // The mCameraDevice will be null if it fails to connect to the camera 1718 // hardware. In this case we will show a dialog and then finish the 1719 // activity, so it's OK to ignore it. 1720 if (mCameraDevice == null) return; 1721 1722 // Sometimes surfaceChanged is called after onPause or before onResume. 1723 // Ignore it. 1724 if (mPausing || isFinishing()) return; 1725 1726 if (mPreviewing && holder.isCreating()) { 1727 // Set preview display if the surface is being created and preview 1728 // was already started. That means preview display was set to null 1729 // and we need to set it now. 1730 setPreviewDisplay(holder); 1731 } else { 1732 // 1. Restart the preview if the size of surface was changed. The 1733 // framework may not support changing preview display on the fly. 1734 // 2. Start the preview now if surface was destroyed and preview 1735 // stopped. 1736 restartPreview(); 1737 } 1738 1739 // If first time initialization is not finished, send a message to do 1740 // it later. We want to finish surfaceChanged as soon as possible to let 1741 // user see preview first. 1742 if (!mFirstTimeInitialized) { 1743 mHandler.sendEmptyMessage(FIRST_TIME_INIT); 1744 } else { 1745 initializeSecondTime(); 1746 } 1747 } 1748 1749 public void surfaceCreated(SurfaceHolder holder) { 1750 } 1751 1752 public void surfaceDestroyed(SurfaceHolder holder) { 1753 stopPreview(); 1754 mSurfaceHolder = null; 1755 } 1756 1757 private void closeCamera() { 1758 if (mCameraDevice != null) { 1759 CameraHolder.instance().release(); 1760 mCameraDevice.setZoomChangeListener(null); 1761 mCameraDevice = null; 1762 mPreviewing = false; 1763 } 1764 } 1765 1766 private void ensureCameraDevice() throws CameraHardwareException { 1767 if (mCameraDevice == null) { 1768 mCameraDevice = CameraHolder.instance().open(mCameraId); 1769 mInitialParams = mCameraDevice.getParameters(); 1770 } 1771 } 1772 1773 private void showCameraErrorAndFinish() { 1774 Resources ress = getResources(); 1775 Util.showFatalErrorAndFinish(Camera.this, 1776 ress.getString(R.string.camera_error_title), 1777 ress.getString(R.string.cannot_connect_camera)); 1778 } 1779 1780 private boolean restartPreview() { 1781 try { 1782 startPreview(); 1783 } catch (CameraHardwareException e) { 1784 showCameraErrorAndFinish(); 1785 return false; 1786 } 1787 return true; 1788 } 1789 1790 private void setPreviewDisplay(SurfaceHolder holder) { 1791 try { 1792 mCameraDevice.setPreviewDisplay(holder); 1793 } catch (Throwable ex) { 1794 closeCamera(); 1795 throw new RuntimeException("setPreviewDisplay failed", ex); 1796 } 1797 } 1798 1799 private void startPreview() throws CameraHardwareException { 1800 if (mPausing || isFinishing()) return; 1801 1802 ensureCameraDevice(); 1803 1804 // If we're previewing already, stop the preview first (this will blank 1805 // the screen). 1806 if (mPreviewing) stopPreview(); 1807 1808 setPreviewDisplay(mSurfaceHolder); 1809 Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice); 1810 setCameraParameters(UPDATE_PARAM_ALL); 1811 1812 mCameraDevice.setErrorCallback(mErrorCallback); 1813 1814 try { 1815 Log.v(TAG, "startPreview"); 1816 mCameraDevice.startPreview(); 1817 } catch (Throwable ex) { 1818 closeCamera(); 1819 throw new RuntimeException("startPreview failed", ex); 1820 } 1821 mPreviewing = true; 1822 mZoomState = ZOOM_STOPPED; 1823 mStatus = IDLE; 1824 } 1825 1826 private void stopPreview() { 1827 if (mCameraDevice != null && mPreviewing) { 1828 Log.v(TAG, "stopPreview"); 1829 mCameraDevice.stopPreview(); 1830 } 1831 mPreviewing = false; 1832 // If auto focus was in progress, it would have been canceled. 1833 clearFocusState(); 1834 } 1835 1836 private static boolean isSupported(String value, List<String> supported) { 1837 return supported == null ? false : supported.indexOf(value) >= 0; 1838 } 1839 1840 private void updateCameraParametersInitialize() { 1841 // Reset preview frame rate to the maximum because it may be lowered by 1842 // video camera application. 1843 List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); 1844 if (frameRates != null) { 1845 Integer max = Collections.max(frameRates); 1846 mParameters.setPreviewFrameRate(max); 1847 } 1848 1849 } 1850 1851 private void updateCameraParametersZoom() { 1852 // Set zoom. 1853 if (mParameters.isZoomSupported()) { 1854 mParameters.setZoom(mZoomValue); 1855 } 1856 } 1857 1858 private void updateCameraParametersPreference() { 1859 // Set picture size. 1860 String pictureSize = mPreferences.getString( 1861 CameraSettings.KEY_PICTURE_SIZE, null); 1862 if (pictureSize == null) { 1863 CameraSettings.initialCameraPictureSize(this, mParameters); 1864 } else { 1865 List<Size> supported = mParameters.getSupportedPictureSizes(); 1866 CameraSettings.setCameraPictureSize( 1867 pictureSize, supported, mParameters); 1868 } 1869 1870 // Set the preview frame aspect ratio according to the picture size. 1871 Size size = mParameters.getPictureSize(); 1872 PreviewFrameLayout frameLayout = 1873 (PreviewFrameLayout) findViewById(R.id.frame_layout); 1874 frameLayout.setAspectRatio((double) size.width / size.height); 1875 1876 // Set a preview size that is closest to the viewfinder height and has 1877 // the right aspect ratio. 1878 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 1879 Size optimalSize = Util.getOptimalPreviewSize(this, 1880 sizes, (double) size.width / size.height); 1881 if (optimalSize != null) { 1882 Size original = mParameters.getPreviewSize(); 1883 if (!original.equals(optimalSize)) { 1884 mParameters.setPreviewSize(optimalSize.width, optimalSize.height); 1885 1886 // Zoom related settings will be changed for different preview 1887 // sizes, so set and read the parameters to get lastest values 1888 mCameraDevice.setParameters(mParameters); 1889 mParameters = mCameraDevice.getParameters(); 1890 } 1891 } 1892 1893 // Since change scene mode may change supported values, 1894 // Set scene mode first, 1895 mSceneMode = mPreferences.getString( 1896 CameraSettings.KEY_SCENE_MODE, 1897 getString(R.string.pref_camera_scenemode_default)); 1898 if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { 1899 if (!mParameters.getSceneMode().equals(mSceneMode)) { 1900 mParameters.setSceneMode(mSceneMode); 1901 mCameraDevice.setParameters(mParameters); 1902 1903 // Setting scene mode will change the settings of flash mode, 1904 // white balance, and focus mode. Here we read back the 1905 // parameters, so we can know those settings. 1906 mParameters = mCameraDevice.getParameters(); 1907 } 1908 } else { 1909 mSceneMode = mParameters.getSceneMode(); 1910 if (mSceneMode == null) { 1911 mSceneMode = Parameters.SCENE_MODE_AUTO; 1912 } 1913 } 1914 1915 // Set JPEG quality. 1916 String jpegQuality = mPreferences.getString( 1917 CameraSettings.KEY_JPEG_QUALITY, 1918 getString(R.string.pref_camera_jpegquality_default)); 1919 mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality)); 1920 1921 // For the following settings, we need to check if the settings are 1922 // still supported by latest driver, if not, ignore the settings. 1923 1924 // Set color effect parameter. 1925 String colorEffect = mPreferences.getString( 1926 CameraSettings.KEY_COLOR_EFFECT, 1927 getString(R.string.pref_camera_coloreffect_default)); 1928 if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) { 1929 mParameters.setColorEffect(colorEffect); 1930 } 1931 1932 // Set exposure compensation 1933 String exposure = mPreferences.getString( 1934 CameraSettings.KEY_EXPOSURE, 1935 getString(R.string.pref_exposure_default)); 1936 try { 1937 int value = Integer.parseInt(exposure); 1938 int max = mParameters.getMaxExposureCompensation(); 1939 int min = mParameters.getMinExposureCompensation(); 1940 if (value >= min && value <= max) { 1941 mParameters.setExposureCompensation(value); 1942 } else { 1943 Log.w(TAG, "invalid exposure range: " + exposure); 1944 } 1945 } catch (NumberFormatException e) { 1946 Log.w(TAG, "invalid exposure: " + exposure); 1947 } 1948 1949 if (mHeadUpDisplay != null) updateSceneModeInHud(); 1950 1951 if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 1952 // Set flash mode. 1953 String flashMode = mPreferences.getString( 1954 CameraSettings.KEY_FLASH_MODE, 1955 getString(R.string.pref_camera_flashmode_default)); 1956 List<String> supportedFlash = mParameters.getSupportedFlashModes(); 1957 if (isSupported(flashMode, supportedFlash)) { 1958 mParameters.setFlashMode(flashMode); 1959 } else { 1960 flashMode = mParameters.getFlashMode(); 1961 if (flashMode == null) { 1962 flashMode = getString( 1963 R.string.pref_camera_flashmode_no_flash); 1964 } 1965 } 1966 1967 // Set white balance parameter. 1968 String whiteBalance = mPreferences.getString( 1969 CameraSettings.KEY_WHITE_BALANCE, 1970 getString(R.string.pref_camera_whitebalance_default)); 1971 if (isSupported(whiteBalance, 1972 mParameters.getSupportedWhiteBalance())) { 1973 mParameters.setWhiteBalance(whiteBalance); 1974 } else { 1975 whiteBalance = mParameters.getWhiteBalance(); 1976 if (whiteBalance == null) { 1977 whiteBalance = Parameters.WHITE_BALANCE_AUTO; 1978 } 1979 } 1980 1981 // Set focus mode. 1982 mFocusMode = mPreferences.getString( 1983 CameraSettings.KEY_FOCUS_MODE, 1984 getString(R.string.pref_camera_focusmode_default)); 1985 if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) { 1986 mParameters.setFocusMode(mFocusMode); 1987 } else { 1988 mFocusMode = mParameters.getFocusMode(); 1989 if (mFocusMode == null) { 1990 mFocusMode = Parameters.FOCUS_MODE_AUTO; 1991 } 1992 } 1993 } else { 1994 mFocusMode = mParameters.getFocusMode(); 1995 } 1996 } 1997 1998 // We separate the parameters into several subsets, so we can update only 1999 // the subsets actually need updating. The PREFERENCE set needs extra 2000 // locking because the preference can be changed from GLThread as well. 2001 private void setCameraParameters(int updateSet) { 2002 mParameters = mCameraDevice.getParameters(); 2003 2004 if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) { 2005 updateCameraParametersInitialize(); 2006 } 2007 2008 if ((updateSet & UPDATE_PARAM_ZOOM) != 0) { 2009 updateCameraParametersZoom(); 2010 } 2011 2012 if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) { 2013 updateCameraParametersPreference(); 2014 } 2015 2016 mCameraDevice.setParameters(mParameters); 2017 } 2018 2019 // If the Camera is idle, update the parameters immediately, otherwise 2020 // accumulate them in mUpdateSet and update later. 2021 private void setCameraParametersWhenIdle(int additionalUpdateSet) { 2022 mUpdateSet |= additionalUpdateSet; 2023 if (mCameraDevice == null) { 2024 // We will update all the parameters when we open the device, so 2025 // we don't need to do anything now. 2026 mUpdateSet = 0; 2027 return; 2028 } else if (isCameraIdle()) { 2029 setCameraParameters(mUpdateSet); 2030 mUpdateSet = 0; 2031 } else { 2032 if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) { 2033 mHandler.sendEmptyMessageDelayed( 2034 SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000); 2035 } 2036 } 2037 } 2038 2039 private void gotoGallery() { 2040 MenuHelper.gotoCameraImageGallery(this); 2041 } 2042 2043 private void viewImage(RotateImageView view) { 2044 if(!view.isUriValid()) { 2045 Log.e(TAG, "Uri invalid. uri=" + view.getUri()); 2046 return; 2047 } 2048 2049 try { 2050 startActivity(new Intent( 2051 Util.REVIEW_ACTION, view.getUri())); 2052 } catch (ActivityNotFoundException ex) { 2053 try { 2054 startActivity(new Intent( 2055 Intent.ACTION_VIEW, view.getUri())); 2056 } catch (ActivityNotFoundException e) { 2057 Log.e(TAG, "review image fail. uri=" + view.getUri(), e); 2058 } 2059 } 2060 } 2061 2062 private void startReceivingLocationUpdates() { 2063 if (mLocationManager != null) { 2064 try { 2065 mLocationManager.requestLocationUpdates( 2066 LocationManager.NETWORK_PROVIDER, 2067 1000, 2068 0F, 2069 mLocationListeners[1]); 2070 } catch (java.lang.SecurityException ex) { 2071 Log.i(TAG, "fail to request location update, ignore", ex); 2072 } catch (IllegalArgumentException ex) { 2073 Log.d(TAG, "provider does not exist " + ex.getMessage()); 2074 } 2075 try { 2076 mLocationManager.requestLocationUpdates( 2077 LocationManager.GPS_PROVIDER, 2078 1000, 2079 0F, 2080 mLocationListeners[0]); 2081 } catch (java.lang.SecurityException ex) { 2082 Log.i(TAG, "fail to request location update, ignore", ex); 2083 } catch (IllegalArgumentException ex) { 2084 Log.d(TAG, "provider does not exist " + ex.getMessage()); 2085 } 2086 } 2087 } 2088 2089 private void stopReceivingLocationUpdates() { 2090 if (mLocationManager != null) { 2091 for (int i = 0; i < mLocationListeners.length; i++) { 2092 try { 2093 mLocationManager.removeUpdates(mLocationListeners[i]); 2094 } catch (Exception ex) { 2095 Log.i(TAG, "fail to remove location listners, ignore", ex); 2096 } 2097 } 2098 } 2099 } 2100 2101 private Location getCurrentLocation() { 2102 // go in best to worst order 2103 for (int i = 0; i < mLocationListeners.length; i++) { 2104 Location l = mLocationListeners[i].current(); 2105 if (l != null) return l; 2106 } 2107 return null; 2108 } 2109 2110 private boolean isCameraIdle() { 2111 return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED; 2112 } 2113 2114 private boolean isImageCaptureIntent() { 2115 String action = getIntent().getAction(); 2116 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); 2117 } 2118 2119 private void setupCaptureParams() { 2120 Bundle myExtras = getIntent().getExtras(); 2121 if (myExtras != null) { 2122 mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 2123 mCropValue = myExtras.getString("crop"); 2124 } 2125 } 2126 2127 private void showPostCaptureAlert() { 2128 if (mIsImageCaptureIntent) { 2129 findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE); 2130 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2131 for (int id : pickIds) { 2132 View button = findViewById(id); 2133 ((View) button.getParent()).setVisibility(View.VISIBLE); 2134 } 2135 } 2136 } 2137 2138 private void hidePostCaptureAlert() { 2139 if (mIsImageCaptureIntent) { 2140 findViewById(R.id.shutter_button).setVisibility(View.VISIBLE); 2141 int[] pickIds = {R.id.btn_retake, R.id.btn_done}; 2142 for (int id : pickIds) { 2143 View button = findViewById(id); 2144 ((View) button.getParent()).setVisibility(View.GONE); 2145 } 2146 } 2147 } 2148 2149 private int calculatePicturesRemaining() { 2150 mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); 2151 return mPicturesRemaining; 2152 } 2153 2154 @Override 2155 public boolean onPrepareOptionsMenu(Menu menu) { 2156 super.onPrepareOptionsMenu(menu); 2157 // Only show the menu when camera is idle. 2158 for (int i = 0; i < menu.size(); i++) { 2159 menu.getItem(i).setVisible(isCameraIdle()); 2160 } 2161 2162 return true; 2163 } 2164 2165 @Override 2166 public boolean onCreateOptionsMenu(Menu menu) { 2167 super.onCreateOptionsMenu(menu); 2168 2169 if (mIsImageCaptureIntent) { 2170 // No options menu for attach mode. 2171 return false; 2172 } else { 2173 addBaseMenuItems(menu); 2174 } 2175 return true; 2176 } 2177 2178 private void addBaseMenuItems(Menu menu) { 2179 MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() { 2180 public void run() { 2181 switchToVideoMode(); 2182 } 2183 }); 2184 MenuItem gallery = menu.add(Menu.NONE, Menu.NONE, 2185 MenuHelper.POSITION_GOTO_GALLERY, 2186 R.string.camera_gallery_photos_text) 2187 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2188 public boolean onMenuItemClick(MenuItem item) { 2189 gotoGallery(); 2190 return true; 2191 } 2192 }); 2193 gallery.setIcon(android.R.drawable.ic_menu_gallery); 2194 mGalleryItems.add(gallery); 2195 2196 if (mNumberOfCameras > 1) { 2197 menu.add(Menu.NONE, Menu.NONE, 2198 MenuHelper.POSITION_SWITCH_CAMERA_ID, 2199 R.string.switch_camera_id) 2200 .setOnMenuItemClickListener(new OnMenuItemClickListener() { 2201 public boolean onMenuItemClick(MenuItem item) { 2202 switchCameraId((mCameraId + 1) % mNumberOfCameras); 2203 return true; 2204 } 2205 }).setIcon(android.R.drawable.ic_menu_camera); 2206 } 2207 } 2208 2209 private void switchCameraId(int cameraId) { 2210 if (mPausing || !isCameraIdle()) return; 2211 mCameraId = cameraId; 2212 CameraSettings.writePreferredCameraId(mPreferences, cameraId); 2213 2214 stopPreview(); 2215 closeCamera(); 2216 2217 // Remove the messages in the event queue. 2218 mHandler.removeMessages(RESTART_PREVIEW); 2219 2220 // Reset variables 2221 mJpegPictureCallbackTime = 0; 2222 mZoomValue = 0; 2223 2224 // Reload the preferences. 2225 mPreferences.setLocalId(this, mCameraId); 2226 CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); 2227 2228 // Restart the preview. 2229 resetExposureCompensation(); 2230 if (!restartPreview()) return; 2231 2232 initializeZoom(); 2233 2234 // Reload the UI. 2235 if (mFirstTimeInitialized) { 2236 initializeHeadUpDisplay(); 2237 } 2238 } 2239 2240 private boolean switchToVideoMode() { 2241 if (isFinishing() || !isCameraIdle()) return false; 2242 MenuHelper.gotoVideoMode(this); 2243 mHandler.removeMessages(FIRST_TIME_INIT); 2244 finish(); 2245 return true; 2246 } 2247 2248 public boolean onSwitchChanged(Switcher source, boolean onOff) { 2249 if (onOff == SWITCH_VIDEO) { 2250 return switchToVideoMode(); 2251 } else { 2252 return true; 2253 } 2254 } 2255 2256 private void onSharedPreferencesChanged() { 2257 // ignore the events after "onPause()" 2258 if (mPausing) return; 2259 2260 boolean recordLocation; 2261 2262 recordLocation = RecordLocationPreference.get( 2263 mPreferences, getContentResolver()); 2264 2265 if (mRecordLocation != recordLocation) { 2266 mRecordLocation = recordLocation; 2267 if (mRecordLocation) { 2268 startReceivingLocationUpdates(); 2269 } else { 2270 stopReceivingLocationUpdates(); 2271 } 2272 } 2273 int cameraId = CameraSettings.readPreferredCameraId(mPreferences); 2274 if (mCameraId != cameraId) { 2275 switchCameraId(cameraId); 2276 } else { 2277 setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE); 2278 } 2279 } 2280 2281 @Override 2282 public void onUserInteraction() { 2283 super.onUserInteraction(); 2284 keepScreenOnAwhile(); 2285 } 2286 2287 private void resetScreenOn() { 2288 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2289 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2290 } 2291 2292 private void keepScreenOnAwhile() { 2293 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 2294 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2295 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 2296 } 2297 2298 private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener { 2299 2300 public void onSharedPreferencesChanged() { 2301 Camera.this.onSharedPreferencesChanged(); 2302 } 2303 2304 public void onRestorePreferencesClicked() { 2305 Camera.this.onRestorePreferencesClicked(); 2306 } 2307 2308 public void onPopupWindowVisibilityChanged(int visibility) { 2309 } 2310 } 2311 2312 protected void onRestorePreferencesClicked() { 2313 if (mPausing) return; 2314 Runnable runnable = new Runnable() { 2315 public void run() { 2316 mHeadUpDisplay.restorePreferences(mParameters); 2317 } 2318 }; 2319 MenuHelper.confirmAction(this, 2320 getString(R.string.confirm_restore_title), 2321 getString(R.string.confirm_restore_message), 2322 runnable); 2323 } 2324 2325 private class MyControlPanelListener implements ControlPanel.Listener { 2326 public void onSharedPreferencesChanged() { 2327 Camera.this.onSharedPreferencesChanged(); 2328 } 2329 } 2330} 2331 2332class FocusRectangle extends View { 2333 2334 @SuppressWarnings("unused") 2335 private static final String TAG = "FocusRectangle"; 2336 2337 public FocusRectangle(Context context, AttributeSet attrs) { 2338 super(context, attrs); 2339 } 2340 2341 private void setDrawable(int resid) { 2342 setBackgroundDrawable(getResources().getDrawable(resid)); 2343 } 2344 2345 public void showStart() { 2346 setDrawable(R.drawable.focus_focusing); 2347 } 2348 2349 public void showSuccess() { 2350 setDrawable(R.drawable.focus_focused); 2351 } 2352 2353 public void showFail() { 2354 setDrawable(R.drawable.focus_focus_failed); 2355 } 2356 2357 public void clear() { 2358 setBackgroundDrawable(null); 2359 } 2360} 2361 2362/* 2363 * Provide a mapping for Jpeg encoding quality levels 2364 * from String representation to numeric representation. 2365 */ 2366class JpegEncodingQualityMappings { 2367 private static final String TAG = "JpegEncodingQualityMappings"; 2368 private static final int DEFAULT_QUALITY = 85; 2369 private static HashMap<String, Integer> mHashMap = 2370 new HashMap<String, Integer>(); 2371 2372 static { 2373 mHashMap.put("normal", CameraProfile.QUALITY_LOW); 2374 mHashMap.put("fine", CameraProfile.QUALITY_MEDIUM); 2375 mHashMap.put("superfine", CameraProfile.QUALITY_HIGH); 2376 } 2377 2378 // Retrieve and return the Jpeg encoding quality number 2379 // for the given quality level. 2380 public static int getQualityNumber(String jpegQuality) { 2381 Integer quality = mHashMap.get(jpegQuality); 2382 if (quality == null) { 2383 Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality); 2384 return DEFAULT_QUALITY; 2385 } 2386 return CameraProfile.getJpegEncodingQualityParameter(quality.intValue()); 2387 } 2388} 2389