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