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