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