Camera.java revision 503e1fdcd12d2448807d408f00a361bff0857cab
1/* 2 * Copyright (C) 2008 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 android.hardware; 18 19import static android.system.OsConstants.*; 20 21import android.annotation.Nullable; 22import android.annotation.SdkConstant; 23import android.annotation.SdkConstant.SdkConstantType; 24import android.app.ActivityThread; 25import android.app.AppOpsManager; 26import android.content.Context; 27import android.graphics.ImageFormat; 28import android.graphics.Point; 29import android.graphics.Rect; 30import android.graphics.SurfaceTexture; 31import android.media.AudioAttributes; 32import android.media.IAudioService; 33import android.os.Handler; 34import android.os.IBinder; 35import android.os.Looper; 36import android.os.Message; 37import android.os.Process; 38import android.os.RemoteException; 39import android.os.ServiceManager; 40import android.renderscript.Allocation; 41import android.renderscript.Element; 42import android.renderscript.RSIllegalArgumentException; 43import android.renderscript.RenderScript; 44import android.renderscript.Type; 45import android.text.TextUtils; 46import android.util.Log; 47import android.view.Surface; 48import android.view.SurfaceHolder; 49 50import com.android.internal.annotations.GuardedBy; 51import com.android.internal.app.IAppOpsCallback; 52import com.android.internal.app.IAppOpsService; 53 54import java.io.IOException; 55import java.lang.ref.WeakReference; 56import java.util.ArrayList; 57import java.util.LinkedHashMap; 58import java.util.List; 59 60/** 61 * The Camera class is used to set image capture settings, start/stop preview, 62 * snap pictures, and retrieve frames for encoding for video. This class is a 63 * client for the Camera service, which manages the actual camera hardware. 64 * 65 * <p>To access the device camera, you must declare the 66 * {@link android.Manifest.permission#CAMERA} permission in your Android 67 * Manifest. Also be sure to include the 68 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 69 * manifest element to declare camera features used by your application. 70 * For example, if you use the camera and auto-focus feature, your Manifest 71 * should include the following:</p> 72 * <pre> <uses-permission android:name="android.permission.CAMERA" /> 73 * <uses-feature android:name="android.hardware.camera" /> 74 * <uses-feature android:name="android.hardware.camera.autofocus" /></pre> 75 * 76 * <p>To take pictures with this class, use the following steps:</p> 77 * 78 * <ol> 79 * <li>Obtain an instance of Camera from {@link #open(int)}. 80 * 81 * <li>Get existing (default) settings with {@link #getParameters()}. 82 * 83 * <li>If necessary, modify the returned {@link Camera.Parameters} object and call 84 * {@link #setParameters(Camera.Parameters)}. 85 * 86 * <li>Call {@link #setDisplayOrientation(int)} to ensure correct orientation of preview. 87 * 88 * <li><b>Important</b>: Pass a fully initialized {@link SurfaceHolder} to 89 * {@link #setPreviewDisplay(SurfaceHolder)}. Without a surface, the camera 90 * will be unable to start the preview. 91 * 92 * <li><b>Important</b>: Call {@link #startPreview()} to start updating the 93 * preview surface. Preview must be started before you can take a picture. 94 * 95 * <li>When you want, call {@link #takePicture(Camera.ShutterCallback, 96 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)} to 97 * capture a photo. Wait for the callbacks to provide the actual image data. 98 * 99 * <li>After taking a picture, preview display will have stopped. To take more 100 * photos, call {@link #startPreview()} again first. 101 * 102 * <li>Call {@link #stopPreview()} to stop updating the preview surface. 103 * 104 * <li><b>Important:</b> Call {@link #release()} to release the camera for 105 * use by other applications. Applications should release the camera 106 * immediately in {@link android.app.Activity#onPause()} (and re-{@link #open()} 107 * it in {@link android.app.Activity#onResume()}). 108 * </ol> 109 * 110 * <p>To quickly switch to video recording mode, use these steps:</p> 111 * 112 * <ol> 113 * <li>Obtain and initialize a Camera and start preview as described above. 114 * 115 * <li>Call {@link #unlock()} to allow the media process to access the camera. 116 * 117 * <li>Pass the camera to {@link android.media.MediaRecorder#setCamera(Camera)}. 118 * See {@link android.media.MediaRecorder} information about video recording. 119 * 120 * <li>When finished recording, call {@link #reconnect()} to re-acquire 121 * and re-lock the camera. 122 * 123 * <li>If desired, restart preview and take more photos or videos. 124 * 125 * <li>Call {@link #stopPreview()} and {@link #release()} as described above. 126 * </ol> 127 * 128 * <p>This class is not thread-safe, and is meant for use from one event thread. 129 * Most long-running operations (preview, focus, photo capture, etc) happen 130 * asynchronously and invoke callbacks as necessary. Callbacks will be invoked 131 * on the event thread {@link #open(int)} was called from. This class's methods 132 * must never be called from multiple threads at once.</p> 133 * 134 * <p class="caution"><strong>Caution:</strong> Different Android-powered devices 135 * may have different hardware specifications, such as megapixel ratings and 136 * auto-focus capabilities. In order for your application to be compatible with 137 * more devices, you should not make assumptions about the device camera 138 * specifications.</p> 139 * 140 * <div class="special reference"> 141 * <h3>Developer Guides</h3> 142 * <p>For more information about using cameras, read the 143 * <a href="{@docRoot}guide/topics/media/camera.html">Camera</a> developer guide.</p> 144 * </div> 145 * 146 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 147 * applications. 148 */ 149@Deprecated 150public class Camera { 151 private static final String TAG = "Camera"; 152 153 // These match the enums in frameworks/base/include/camera/Camera.h 154 private static final int CAMERA_MSG_ERROR = 0x001; 155 private static final int CAMERA_MSG_SHUTTER = 0x002; 156 private static final int CAMERA_MSG_FOCUS = 0x004; 157 private static final int CAMERA_MSG_ZOOM = 0x008; 158 private static final int CAMERA_MSG_PREVIEW_FRAME = 0x010; 159 private static final int CAMERA_MSG_VIDEO_FRAME = 0x020; 160 private static final int CAMERA_MSG_POSTVIEW_FRAME = 0x040; 161 private static final int CAMERA_MSG_RAW_IMAGE = 0x080; 162 private static final int CAMERA_MSG_COMPRESSED_IMAGE = 0x100; 163 private static final int CAMERA_MSG_RAW_IMAGE_NOTIFY = 0x200; 164 private static final int CAMERA_MSG_PREVIEW_METADATA = 0x400; 165 private static final int CAMERA_MSG_FOCUS_MOVE = 0x800; 166 167 private long mNativeContext; // accessed by native methods 168 private EventHandler mEventHandler; 169 private ShutterCallback mShutterCallback; 170 private PictureCallback mRawImageCallback; 171 private PictureCallback mJpegCallback; 172 private PreviewCallback mPreviewCallback; 173 private boolean mUsingPreviewAllocation; 174 private PictureCallback mPostviewCallback; 175 private AutoFocusCallback mAutoFocusCallback; 176 private AutoFocusMoveCallback mAutoFocusMoveCallback; 177 private OnZoomChangeListener mZoomListener; 178 private FaceDetectionListener mFaceListener; 179 private ErrorCallback mErrorCallback; 180 private boolean mOneShot; 181 private boolean mWithBuffer; 182 private boolean mFaceDetectionRunning = false; 183 private final Object mAutoFocusCallbackLock = new Object(); 184 185 private final Object mShutterSoundLock = new Object(); 186 // for AppOps 187 private @Nullable IAppOpsService mAppOps; 188 private IAppOpsCallback mAppOpsCallback; 189 @GuardedBy("mShutterSoundLock") 190 private boolean mHasAppOpsPlayAudio = true; 191 @GuardedBy("mShutterSoundLock") 192 private boolean mShutterSoundEnabledFromApp = true; 193 194 private static final int NO_ERROR = 0; 195 196 /** 197 * Broadcast Action: A new picture is taken by the camera, and the entry of 198 * the picture has been added to the media store. 199 * {@link android.content.Intent#getData} is URI of the picture. 200 * 201 * <p>In {@link android.os.Build.VERSION_CODES#N Android N} this broadcast was removed, and 202 * applications are recommended to use 203 * {@link android.app.job.JobInfo.Builder JobInfo.Builder}.{@link android.app.job.JobInfo.Builder#addTriggerContentUri} 204 * instead.</p> 205 * 206 * <p>In {@link android.os.Build.VERSION_CODES#O Android O} this broadcast has been brought 207 * back, but only for <em>registered</em> receivers. Apps that are actively running can 208 * again listen to the broadcast if they want an immediate clear signal about a picture 209 * being taken, however anything doing heavy work (or needing to be launched) as a result of 210 * this should still use JobScheduler.</p> 211 */ 212 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 213 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE"; 214 215 /** 216 * Broadcast Action: A new video is recorded by the camera, and the entry 217 * of the video has been added to the media store. 218 * {@link android.content.Intent#getData} is URI of the video. 219 * 220 * <p>In {@link android.os.Build.VERSION_CODES#N Android N} this broadcast was removed, and 221 * applications are recommended to use 222 * {@link android.app.job.JobInfo.Builder JobInfo.Builder}.{@link android.app.job.JobInfo.Builder#addTriggerContentUri} 223 * instead.</p> 224 * 225 * <p>In {@link android.os.Build.VERSION_CODES#O Android O} this broadcast has been brought 226 * back, but only for <em>registered</em> receivers. Apps that are actively running can 227 * again listen to the broadcast if they want an immediate clear signal about a video 228 * being taken, however anything doing heavy work (or needing to be launched) as a result of 229 * this should still use JobScheduler.</p> 230 */ 231 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 232 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO"; 233 234 /** 235 * Camera HAL device API version 1.0 236 * @hide 237 */ 238 public static final int CAMERA_HAL_API_VERSION_1_0 = 0x100; 239 240 /** 241 * A constant meaning the normal camera connect/open will be used. 242 */ 243 private static final int CAMERA_HAL_API_VERSION_NORMAL_CONNECT = -2; 244 245 /** 246 * Used to indicate HAL version un-specified. 247 */ 248 private static final int CAMERA_HAL_API_VERSION_UNSPECIFIED = -1; 249 250 /** 251 * Hardware face detection. It does not use much CPU. 252 */ 253 private static final int CAMERA_FACE_DETECTION_HW = 0; 254 255 /** 256 * Software face detection. It uses some CPU. 257 */ 258 private static final int CAMERA_FACE_DETECTION_SW = 1; 259 260 /** 261 * Returns the number of physical cameras available on this device. 262 * The return value of this method might change dynamically if the device 263 * supports external cameras and an external camera is connected or 264 * disconnected. 265 * 266 * @return total number of accessible camera devices, or 0 if there are no 267 * cameras or an error was encountered enumerating them. 268 */ 269 public native static int getNumberOfCameras(); 270 271 /** 272 * Returns the information about a particular camera. 273 * If {@link #getNumberOfCameras()} returns N, the valid id is 0 to N-1. 274 * 275 * @throws RuntimeException if an invalid ID is provided, or if there is an 276 * error retrieving the information (generally due to a hardware or other 277 * low-level failure). 278 */ 279 public static void getCameraInfo(int cameraId, CameraInfo cameraInfo) { 280 _getCameraInfo(cameraId, cameraInfo); 281 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE); 282 IAudioService audioService = IAudioService.Stub.asInterface(b); 283 try { 284 if (audioService.isCameraSoundForced()) { 285 // Only set this when sound is forced; otherwise let native code 286 // decide. 287 cameraInfo.canDisableShutterSound = false; 288 } 289 } catch (RemoteException e) { 290 Log.e(TAG, "Audio service is unavailable for queries"); 291 } 292 } 293 private native static void _getCameraInfo(int cameraId, CameraInfo cameraInfo); 294 295 /** 296 * Information about a camera 297 * 298 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 299 * applications. 300 */ 301 @Deprecated 302 public static class CameraInfo { 303 /** 304 * The facing of the camera is opposite to that of the screen. 305 */ 306 public static final int CAMERA_FACING_BACK = 0; 307 308 /** 309 * The facing of the camera is the same as that of the screen. 310 */ 311 public static final int CAMERA_FACING_FRONT = 1; 312 313 /** 314 * The direction that the camera faces. It should be 315 * CAMERA_FACING_BACK or CAMERA_FACING_FRONT. 316 */ 317 public int facing; 318 319 /** 320 * <p>The orientation of the camera image. The value is the angle that the 321 * camera image needs to be rotated clockwise so it shows correctly on 322 * the display in its natural orientation. It should be 0, 90, 180, or 270.</p> 323 * 324 * <p>For example, suppose a device has a naturally tall screen. The 325 * back-facing camera sensor is mounted in landscape. You are looking at 326 * the screen. If the top side of the camera sensor is aligned with the 327 * right edge of the screen in natural orientation, the value should be 328 * 90. If the top side of a front-facing camera sensor is aligned with 329 * the right of the screen, the value should be 270.</p> 330 * 331 * @see #setDisplayOrientation(int) 332 * @see Parameters#setRotation(int) 333 * @see Parameters#setPreviewSize(int, int) 334 * @see Parameters#setPictureSize(int, int) 335 * @see Parameters#setJpegThumbnailSize(int, int) 336 */ 337 public int orientation; 338 339 /** 340 * <p>Whether the shutter sound can be disabled.</p> 341 * 342 * <p>On some devices, the camera shutter sound cannot be turned off 343 * through {@link #enableShutterSound enableShutterSound}. This field 344 * can be used to determine whether a call to disable the shutter sound 345 * will succeed.</p> 346 * 347 * <p>If this field is set to true, then a call of 348 * {@code enableShutterSound(false)} will be successful. If set to 349 * false, then that call will fail, and the shutter sound will be played 350 * when {@link Camera#takePicture takePicture} is called.</p> 351 */ 352 public boolean canDisableShutterSound; 353 }; 354 355 /** 356 * Creates a new Camera object to access a particular hardware camera. If 357 * the same camera is opened by other applications, this will throw a 358 * RuntimeException. 359 * 360 * <p>You must call {@link #release()} when you are done using the camera, 361 * otherwise it will remain locked and be unavailable to other applications. 362 * 363 * <p>Your application should only have one Camera object active at a time 364 * for a particular hardware camera. 365 * 366 * <p>Callbacks from other methods are delivered to the event loop of the 367 * thread which called open(). If this thread has no event loop, then 368 * callbacks are delivered to the main application event loop. If there 369 * is no main application event loop, callbacks are not delivered. 370 * 371 * <p class="caution"><b>Caution:</b> On some devices, this method may 372 * take a long time to complete. It is best to call this method from a 373 * worker thread (possibly using {@link android.os.AsyncTask}) to avoid 374 * blocking the main application UI thread. 375 * 376 * @param cameraId the hardware camera to access, between 0 and 377 * {@link #getNumberOfCameras()}-1. 378 * @return a new Camera object, connected, locked and ready for use. 379 * @throws RuntimeException if opening the camera fails (for example, if the 380 * camera is in use by another process or device policy manager has 381 * disabled the camera). 382 * @see android.app.admin.DevicePolicyManager#getCameraDisabled(android.content.ComponentName) 383 */ 384 public static Camera open(int cameraId) { 385 return new Camera(cameraId); 386 } 387 388 /** 389 * Creates a new Camera object to access the first back-facing camera on the 390 * device. If the device does not have a back-facing camera, this returns 391 * null. Otherwise acts like the {@link #open(int)} call. 392 * 393 * @return a new Camera object for the first back-facing camera, or null if there is no 394 * backfacing camera 395 * @see #open(int) 396 */ 397 public static Camera open() { 398 int numberOfCameras = getNumberOfCameras(); 399 CameraInfo cameraInfo = new CameraInfo(); 400 for (int i = 0; i < numberOfCameras; i++) { 401 getCameraInfo(i, cameraInfo); 402 if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { 403 return new Camera(i); 404 } 405 } 406 return null; 407 } 408 409 /** 410 * Creates a new Camera object to access a particular hardware camera with 411 * given hal API version. If the same camera is opened by other applications 412 * or the hal API version is not supported by this device, this will throw a 413 * RuntimeException. 414 * <p> 415 * You must call {@link #release()} when you are done using the camera, 416 * otherwise it will remain locked and be unavailable to other applications. 417 * <p> 418 * Your application should only have one Camera object active at a time for 419 * a particular hardware camera. 420 * <p> 421 * Callbacks from other methods are delivered to the event loop of the 422 * thread which called open(). If this thread has no event loop, then 423 * callbacks are delivered to the main application event loop. If there is 424 * no main application event loop, callbacks are not delivered. 425 * <p class="caution"> 426 * <b>Caution:</b> On some devices, this method may take a long time to 427 * complete. It is best to call this method from a worker thread (possibly 428 * using {@link android.os.AsyncTask}) to avoid blocking the main 429 * application UI thread. 430 * 431 * @param cameraId The hardware camera to access, between 0 and 432 * {@link #getNumberOfCameras()}-1. 433 * @param halVersion The HAL API version this camera device to be opened as. 434 * @return a new Camera object, connected, locked and ready for use. 435 * 436 * @throws IllegalArgumentException if the {@code halVersion} is invalid 437 * 438 * @throws RuntimeException if opening the camera fails (for example, if the 439 * camera is in use by another process or device policy manager has disabled 440 * the camera). 441 * 442 * @see android.app.admin.DevicePolicyManager#getCameraDisabled(android.content.ComponentName) 443 * @see #CAMERA_HAL_API_VERSION_1_0 444 * 445 * @hide 446 */ 447 public static Camera openLegacy(int cameraId, int halVersion) { 448 if (halVersion < CAMERA_HAL_API_VERSION_1_0) { 449 throw new IllegalArgumentException("Invalid HAL version " + halVersion); 450 } 451 452 return new Camera(cameraId, halVersion); 453 } 454 455 /** 456 * Create a legacy camera object. 457 * 458 * @param cameraId The hardware camera to access, between 0 and 459 * {@link #getNumberOfCameras()}-1. 460 * @param halVersion The HAL API version this camera device to be opened as. 461 */ 462 private Camera(int cameraId, int halVersion) { 463 int err = cameraInitVersion(cameraId, halVersion); 464 if (checkInitErrors(err)) { 465 if (err == -EACCES) { 466 throw new RuntimeException("Fail to connect to camera service"); 467 } else if (err == -ENODEV) { 468 throw new RuntimeException("Camera initialization failed"); 469 } else if (err == -ENOSYS) { 470 throw new RuntimeException("Camera initialization failed because some methods" 471 + " are not implemented"); 472 } else if (err == -EOPNOTSUPP) { 473 throw new RuntimeException("Camera initialization failed because the hal" 474 + " version is not supported by this device"); 475 } else if (err == -EINVAL) { 476 throw new RuntimeException("Camera initialization failed because the input" 477 + " arugments are invalid"); 478 } else if (err == -EBUSY) { 479 throw new RuntimeException("Camera initialization failed because the camera" 480 + " device was already opened"); 481 } else if (err == -EUSERS) { 482 throw new RuntimeException("Camera initialization failed because the max" 483 + " number of camera devices were already opened"); 484 } 485 // Should never hit this. 486 throw new RuntimeException("Unknown camera error"); 487 } 488 } 489 490 private int cameraInitVersion(int cameraId, int halVersion) { 491 mShutterCallback = null; 492 mRawImageCallback = null; 493 mJpegCallback = null; 494 mPreviewCallback = null; 495 mPostviewCallback = null; 496 mUsingPreviewAllocation = false; 497 mZoomListener = null; 498 499 Looper looper; 500 if ((looper = Looper.myLooper()) != null) { 501 mEventHandler = new EventHandler(this, looper); 502 } else if ((looper = Looper.getMainLooper()) != null) { 503 mEventHandler = new EventHandler(this, looper); 504 } else { 505 mEventHandler = null; 506 } 507 508 return native_setup(new WeakReference<Camera>(this), cameraId, halVersion, 509 ActivityThread.currentOpPackageName()); 510 } 511 512 private int cameraInitNormal(int cameraId) { 513 return cameraInitVersion(cameraId, CAMERA_HAL_API_VERSION_NORMAL_CONNECT); 514 } 515 516 /** 517 * Connect to the camera service using #connectLegacy 518 * 519 * <p> 520 * This acts the same as normal except that it will return 521 * the detailed error code if open fails instead of 522 * converting everything into {@code NO_INIT}.</p> 523 * 524 * <p>Intended to use by the camera2 shim only, do <i>not</i> use this for other code.</p> 525 * 526 * @return a detailed errno error code, or {@code NO_ERROR} on success 527 * 528 * @hide 529 */ 530 public int cameraInitUnspecified(int cameraId) { 531 return cameraInitVersion(cameraId, CAMERA_HAL_API_VERSION_UNSPECIFIED); 532 } 533 534 /** used by Camera#open, Camera#open(int) */ 535 Camera(int cameraId) { 536 int err = cameraInitNormal(cameraId); 537 if (checkInitErrors(err)) { 538 if (err == -EACCES) { 539 throw new RuntimeException("Fail to connect to camera service"); 540 } else if (err == -ENODEV) { 541 throw new RuntimeException("Camera initialization failed"); 542 } 543 // Should never hit this. 544 throw new RuntimeException("Unknown camera error"); 545 } 546 initAppOps(); 547 } 548 549 550 /** 551 * @hide 552 */ 553 public static boolean checkInitErrors(int err) { 554 return err != NO_ERROR; 555 } 556 557 /** 558 * @hide 559 */ 560 public static Camera openUninitialized() { 561 return new Camera(); 562 } 563 564 /** 565 * An empty Camera for testing purpose. 566 */ 567 Camera() { 568 initAppOps(); 569 } 570 571 private void initAppOps() { 572 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE); 573 mAppOps = IAppOpsService.Stub.asInterface(b); 574 // initialize mHasAppOpsPlayAudio 575 updateAppOpsPlayAudio(); 576 // register a callback to monitor whether the OP_PLAY_AUDIO is still allowed 577 mAppOpsCallback = new IAppOpsCallbackWrapper(this); 578 try { 579 mAppOps.startWatchingMode(AppOpsManager.OP_PLAY_AUDIO, 580 ActivityThread.currentPackageName(), mAppOpsCallback); 581 } catch (RemoteException e) { 582 Log.e(TAG, "Error registering appOps callback", e); 583 mHasAppOpsPlayAudio = false; 584 } 585 } 586 587 private void releaseAppOps() { 588 try { 589 if (mAppOps != null) { 590 mAppOps.stopWatchingMode(mAppOpsCallback); 591 } 592 } catch (Exception e) { 593 // nothing to do here, the object is supposed to be released anyway 594 } 595 } 596 597 @Override 598 protected void finalize() { 599 release(); 600 } 601 602 private native final int native_setup(Object camera_this, int cameraId, int halVersion, 603 String packageName); 604 605 private native final void native_release(); 606 607 608 /** 609 * Disconnects and releases the Camera object resources. 610 * 611 * <p>You must call this as soon as you're done with the Camera object.</p> 612 */ 613 public final void release() { 614 native_release(); 615 mFaceDetectionRunning = false; 616 releaseAppOps(); 617 } 618 619 /** 620 * Unlocks the camera to allow another process to access it. 621 * Normally, the camera is locked to the process with an active Camera 622 * object until {@link #release()} is called. To allow rapid handoff 623 * between processes, you can call this method to release the camera 624 * temporarily for another process to use; once the other process is done 625 * you can call {@link #reconnect()} to reclaim the camera. 626 * 627 * <p>This must be done before calling 628 * {@link android.media.MediaRecorder#setCamera(Camera)}. This cannot be 629 * called after recording starts. 630 * 631 * <p>If you are not recording video, you probably do not need this method. 632 * 633 * @throws RuntimeException if the camera cannot be unlocked. 634 */ 635 public native final void unlock(); 636 637 /** 638 * Re-locks the camera to prevent other processes from accessing it. 639 * Camera objects are locked by default unless {@link #unlock()} is 640 * called. Normally {@link #reconnect()} is used instead. 641 * 642 * <p>Since API level 14, camera is automatically locked for applications in 643 * {@link android.media.MediaRecorder#start()}. Applications can use the 644 * camera (ex: zoom) after recording starts. There is no need to call this 645 * after recording starts or stops. 646 * 647 * <p>If you are not recording video, you probably do not need this method. 648 * 649 * @throws RuntimeException if the camera cannot be re-locked (for 650 * example, if the camera is still in use by another process). 651 */ 652 public native final void lock(); 653 654 /** 655 * Reconnects to the camera service after another process used it. 656 * After {@link #unlock()} is called, another process may use the 657 * camera; when the process is done, you must reconnect to the camera, 658 * which will re-acquire the lock and allow you to continue using the 659 * camera. 660 * 661 * <p>Since API level 14, camera is automatically locked for applications in 662 * {@link android.media.MediaRecorder#start()}. Applications can use the 663 * camera (ex: zoom) after recording starts. There is no need to call this 664 * after recording starts or stops. 665 * 666 * <p>If you are not recording video, you probably do not need this method. 667 * 668 * @throws IOException if a connection cannot be re-established (for 669 * example, if the camera is still in use by another process). 670 * @throws RuntimeException if release() has been called on this Camera 671 * instance. 672 */ 673 public native final void reconnect() throws IOException; 674 675 /** 676 * Sets the {@link Surface} to be used for live preview. 677 * Either a surface or surface texture is necessary for preview, and 678 * preview is necessary to take pictures. The same surface can be re-set 679 * without harm. Setting a preview surface will un-set any preview surface 680 * texture that was set via {@link #setPreviewTexture}. 681 * 682 * <p>The {@link SurfaceHolder} must already contain a surface when this 683 * method is called. If you are using {@link android.view.SurfaceView}, 684 * you will need to register a {@link SurfaceHolder.Callback} with 685 * {@link SurfaceHolder#addCallback(SurfaceHolder.Callback)} and wait for 686 * {@link SurfaceHolder.Callback#surfaceCreated(SurfaceHolder)} before 687 * calling setPreviewDisplay() or starting preview. 688 * 689 * <p>This method must be called before {@link #startPreview()}. The 690 * one exception is that if the preview surface is not set (or set to null) 691 * before startPreview() is called, then this method may be called once 692 * with a non-null parameter to set the preview surface. (This allows 693 * camera setup and surface creation to happen in parallel, saving time.) 694 * The preview surface may not otherwise change while preview is running. 695 * 696 * @param holder containing the Surface on which to place the preview, 697 * or null to remove the preview surface 698 * @throws IOException if the method fails (for example, if the surface 699 * is unavailable or unsuitable). 700 * @throws RuntimeException if release() has been called on this Camera 701 * instance. 702 */ 703 public final void setPreviewDisplay(SurfaceHolder holder) throws IOException { 704 if (holder != null) { 705 setPreviewSurface(holder.getSurface()); 706 } else { 707 setPreviewSurface((Surface)null); 708 } 709 } 710 711 /** 712 * @hide 713 */ 714 public native final void setPreviewSurface(Surface surface) throws IOException; 715 716 /** 717 * Sets the {@link SurfaceTexture} to be used for live preview. 718 * Either a surface or surface texture is necessary for preview, and 719 * preview is necessary to take pictures. The same surface texture can be 720 * re-set without harm. Setting a preview surface texture will un-set any 721 * preview surface that was set via {@link #setPreviewDisplay}. 722 * 723 * <p>This method must be called before {@link #startPreview()}. The 724 * one exception is that if the preview surface texture is not set (or set 725 * to null) before startPreview() is called, then this method may be called 726 * once with a non-null parameter to set the preview surface. (This allows 727 * camera setup and surface creation to happen in parallel, saving time.) 728 * The preview surface texture may not otherwise change while preview is 729 * running. 730 * 731 * <p>The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a 732 * SurfaceTexture set as the preview texture have an unspecified zero point, 733 * and cannot be directly compared between different cameras or different 734 * instances of the same camera, or across multiple runs of the same 735 * program. 736 * 737 * <p>If you are using the preview data to create video or still images, 738 * strongly consider using {@link android.media.MediaActionSound} to 739 * properly indicate image capture or recording start/stop to the user.</p> 740 * 741 * @see android.media.MediaActionSound 742 * @see android.graphics.SurfaceTexture 743 * @see android.view.TextureView 744 * @param surfaceTexture the {@link SurfaceTexture} to which the preview 745 * images are to be sent or null to remove the current preview surface 746 * texture 747 * @throws IOException if the method fails (for example, if the surface 748 * texture is unavailable or unsuitable). 749 * @throws RuntimeException if release() has been called on this Camera 750 * instance. 751 */ 752 public native final void setPreviewTexture(SurfaceTexture surfaceTexture) throws IOException; 753 754 /** 755 * Callback interface used to deliver copies of preview frames as 756 * they are displayed. 757 * 758 * @see #setPreviewCallback(Camera.PreviewCallback) 759 * @see #setOneShotPreviewCallback(Camera.PreviewCallback) 760 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 761 * @see #startPreview() 762 * 763 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 764 * applications. 765 */ 766 @Deprecated 767 public interface PreviewCallback 768 { 769 /** 770 * Called as preview frames are displayed. This callback is invoked 771 * on the event thread {@link #open(int)} was called from. 772 * 773 * <p>If using the {@link android.graphics.ImageFormat#YV12} format, 774 * refer to the equations in {@link Camera.Parameters#setPreviewFormat} 775 * for the arrangement of the pixel data in the preview callback 776 * buffers. 777 * 778 * @param data the contents of the preview frame in the format defined 779 * by {@link android.graphics.ImageFormat}, which can be queried 780 * with {@link android.hardware.Camera.Parameters#getPreviewFormat()}. 781 * If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)} 782 * is never called, the default will be the YCbCr_420_SP 783 * (NV21) format. 784 * @param camera the Camera service object. 785 */ 786 void onPreviewFrame(byte[] data, Camera camera); 787 }; 788 789 /** 790 * Starts capturing and drawing preview frames to the screen. 791 * Preview will not actually start until a surface is supplied 792 * with {@link #setPreviewDisplay(SurfaceHolder)} or 793 * {@link #setPreviewTexture(SurfaceTexture)}. 794 * 795 * <p>If {@link #setPreviewCallback(Camera.PreviewCallback)}, 796 * {@link #setOneShotPreviewCallback(Camera.PreviewCallback)}, or 797 * {@link #setPreviewCallbackWithBuffer(Camera.PreviewCallback)} were 798 * called, {@link Camera.PreviewCallback#onPreviewFrame(byte[], Camera)} 799 * will be called when preview data becomes available. 800 * 801 * @throws RuntimeException if starting preview fails; usually this would be 802 * because of a hardware or other low-level error, or because release() 803 * has been called on this Camera instance. 804 */ 805 public native final void startPreview(); 806 807 /** 808 * Stops capturing and drawing preview frames to the surface, and 809 * resets the camera for a future call to {@link #startPreview()}. 810 * 811 * @throws RuntimeException if stopping preview fails; usually this would be 812 * because of a hardware or other low-level error, or because release() 813 * has been called on this Camera instance. 814 */ 815 public final void stopPreview() { 816 _stopPreview(); 817 mFaceDetectionRunning = false; 818 819 mShutterCallback = null; 820 mRawImageCallback = null; 821 mPostviewCallback = null; 822 mJpegCallback = null; 823 synchronized (mAutoFocusCallbackLock) { 824 mAutoFocusCallback = null; 825 } 826 mAutoFocusMoveCallback = null; 827 } 828 829 private native final void _stopPreview(); 830 831 /** 832 * Return current preview state. 833 * 834 * FIXME: Unhide before release 835 * @hide 836 */ 837 public native final boolean previewEnabled(); 838 839 /** 840 * <p>Installs a callback to be invoked for every preview frame in addition 841 * to displaying them on the screen. The callback will be repeatedly called 842 * for as long as preview is active. This method can be called at any time, 843 * even while preview is live. Any other preview callbacks are 844 * overridden.</p> 845 * 846 * <p>If you are using the preview data to create video or still images, 847 * strongly consider using {@link android.media.MediaActionSound} to 848 * properly indicate image capture or recording start/stop to the user.</p> 849 * 850 * @param cb a callback object that receives a copy of each preview frame, 851 * or null to stop receiving callbacks. 852 * @throws RuntimeException if release() has been called on this Camera 853 * instance. 854 * @see android.media.MediaActionSound 855 */ 856 public final void setPreviewCallback(PreviewCallback cb) { 857 mPreviewCallback = cb; 858 mOneShot = false; 859 mWithBuffer = false; 860 if (cb != null) { 861 mUsingPreviewAllocation = false; 862 } 863 // Always use one-shot mode. We fake camera preview mode by 864 // doing one-shot preview continuously. 865 setHasPreviewCallback(cb != null, false); 866 } 867 868 /** 869 * <p>Installs a callback to be invoked for the next preview frame in 870 * addition to displaying it on the screen. After one invocation, the 871 * callback is cleared. This method can be called any time, even when 872 * preview is live. Any other preview callbacks are overridden.</p> 873 * 874 * <p>If you are using the preview data to create video or still images, 875 * strongly consider using {@link android.media.MediaActionSound} to 876 * properly indicate image capture or recording start/stop to the user.</p> 877 * 878 * @param cb a callback object that receives a copy of the next preview frame, 879 * or null to stop receiving callbacks. 880 * @throws RuntimeException if release() has been called on this Camera 881 * instance. 882 * @see android.media.MediaActionSound 883 */ 884 public final void setOneShotPreviewCallback(PreviewCallback cb) { 885 mPreviewCallback = cb; 886 mOneShot = true; 887 mWithBuffer = false; 888 if (cb != null) { 889 mUsingPreviewAllocation = false; 890 } 891 setHasPreviewCallback(cb != null, false); 892 } 893 894 private native final void setHasPreviewCallback(boolean installed, boolean manualBuffer); 895 896 /** 897 * <p>Installs a callback to be invoked for every preview frame, using 898 * buffers supplied with {@link #addCallbackBuffer(byte[])}, in addition to 899 * displaying them on the screen. The callback will be repeatedly called 900 * for as long as preview is active and buffers are available. Any other 901 * preview callbacks are overridden.</p> 902 * 903 * <p>The purpose of this method is to improve preview efficiency and frame 904 * rate by allowing preview frame memory reuse. You must call 905 * {@link #addCallbackBuffer(byte[])} at some point -- before or after 906 * calling this method -- or no callbacks will received.</p> 907 * 908 * <p>The buffer queue will be cleared if this method is called with a null 909 * callback, {@link #setPreviewCallback(Camera.PreviewCallback)} is called, 910 * or {@link #setOneShotPreviewCallback(Camera.PreviewCallback)} is 911 * called.</p> 912 * 913 * <p>If you are using the preview data to create video or still images, 914 * strongly consider using {@link android.media.MediaActionSound} to 915 * properly indicate image capture or recording start/stop to the user.</p> 916 * 917 * @param cb a callback object that receives a copy of the preview frame, 918 * or null to stop receiving callbacks and clear the buffer queue. 919 * @throws RuntimeException if release() has been called on this Camera 920 * instance. 921 * @see #addCallbackBuffer(byte[]) 922 * @see android.media.MediaActionSound 923 */ 924 public final void setPreviewCallbackWithBuffer(PreviewCallback cb) { 925 mPreviewCallback = cb; 926 mOneShot = false; 927 mWithBuffer = true; 928 if (cb != null) { 929 mUsingPreviewAllocation = false; 930 } 931 setHasPreviewCallback(cb != null, true); 932 } 933 934 /** 935 * Adds a pre-allocated buffer to the preview callback buffer queue. 936 * Applications can add one or more buffers to the queue. When a preview 937 * frame arrives and there is still at least one available buffer, the 938 * buffer will be used and removed from the queue. Then preview callback is 939 * invoked with the buffer. If a frame arrives and there is no buffer left, 940 * the frame is discarded. Applications should add buffers back when they 941 * finish processing the data in them. 942 * 943 * <p>For formats besides YV12, the size of the buffer is determined by 944 * multiplying the preview image width, height, and bytes per pixel. The 945 * width and height can be read from 946 * {@link Camera.Parameters#getPreviewSize()}. Bytes per pixel can be 947 * computed from {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 948 * 8, using the image format from 949 * {@link Camera.Parameters#getPreviewFormat()}. 950 * 951 * <p>If using the {@link android.graphics.ImageFormat#YV12} format, the 952 * size can be calculated using the equations listed in 953 * {@link Camera.Parameters#setPreviewFormat}. 954 * 955 * <p>This method is only necessary when 956 * {@link #setPreviewCallbackWithBuffer(PreviewCallback)} is used. When 957 * {@link #setPreviewCallback(PreviewCallback)} or 958 * {@link #setOneShotPreviewCallback(PreviewCallback)} are used, buffers 959 * are automatically allocated. When a supplied buffer is too small to 960 * hold the preview frame data, preview callback will return null and 961 * the buffer will be removed from the buffer queue. 962 * 963 * @param callbackBuffer the buffer to add to the queue. The size of the 964 * buffer must match the values described above. 965 * @see #setPreviewCallbackWithBuffer(PreviewCallback) 966 */ 967 public final void addCallbackBuffer(byte[] callbackBuffer) 968 { 969 _addCallbackBuffer(callbackBuffer, CAMERA_MSG_PREVIEW_FRAME); 970 } 971 972 /** 973 * Adds a pre-allocated buffer to the raw image callback buffer queue. 974 * Applications can add one or more buffers to the queue. When a raw image 975 * frame arrives and there is still at least one available buffer, the 976 * buffer will be used to hold the raw image data and removed from the 977 * queue. Then raw image callback is invoked with the buffer. If a raw 978 * image frame arrives but there is no buffer left, the frame is 979 * discarded. Applications should add buffers back when they finish 980 * processing the data in them by calling this method again in order 981 * to avoid running out of raw image callback buffers. 982 * 983 * <p>The size of the buffer is determined by multiplying the raw image 984 * width, height, and bytes per pixel. The width and height can be 985 * read from {@link Camera.Parameters#getPictureSize()}. Bytes per pixel 986 * can be computed from 987 * {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, 988 * using the image format from {@link Camera.Parameters#getPreviewFormat()}. 989 * 990 * <p>This method is only necessary when the PictureCallbck for raw image 991 * is used while calling {@link #takePicture(Camera.ShutterCallback, 992 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. 993 * 994 * <p>Please note that by calling this method, the mode for 995 * application-managed callback buffers is triggered. If this method has 996 * never been called, null will be returned by the raw image callback since 997 * there is no image callback buffer available. Furthermore, When a supplied 998 * buffer is too small to hold the raw image data, raw image callback will 999 * return null and the buffer will be removed from the buffer queue. 1000 * 1001 * @param callbackBuffer the buffer to add to the raw image callback buffer 1002 * queue. The size should be width * height * (bits per pixel) / 8. An 1003 * null callbackBuffer will be ignored and won't be added to the queue. 1004 * 1005 * @see #takePicture(Camera.ShutterCallback, 1006 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. 1007 * 1008 * {@hide} 1009 */ 1010 public final void addRawImageCallbackBuffer(byte[] callbackBuffer) 1011 { 1012 addCallbackBuffer(callbackBuffer, CAMERA_MSG_RAW_IMAGE); 1013 } 1014 1015 private final void addCallbackBuffer(byte[] callbackBuffer, int msgType) 1016 { 1017 // CAMERA_MSG_VIDEO_FRAME may be allowed in the future. 1018 if (msgType != CAMERA_MSG_PREVIEW_FRAME && 1019 msgType != CAMERA_MSG_RAW_IMAGE) { 1020 throw new IllegalArgumentException( 1021 "Unsupported message type: " + msgType); 1022 } 1023 1024 _addCallbackBuffer(callbackBuffer, msgType); 1025 } 1026 1027 private native final void _addCallbackBuffer( 1028 byte[] callbackBuffer, int msgType); 1029 1030 /** 1031 * <p>Create a {@link android.renderscript RenderScript} 1032 * {@link android.renderscript.Allocation Allocation} to use as a 1033 * destination of preview callback frames. Use 1034 * {@link #setPreviewCallbackAllocation setPreviewCallbackAllocation} to use 1035 * the created Allocation as a destination for camera preview frames.</p> 1036 * 1037 * <p>The Allocation will be created with a YUV type, and its contents must 1038 * be accessed within Renderscript with the {@code rsGetElementAtYuv_*} 1039 * accessor methods. Its size will be based on the current 1040 * {@link Parameters#getPreviewSize preview size} configured for this 1041 * camera.</p> 1042 * 1043 * @param rs the RenderScript context for this Allocation. 1044 * @param usage additional usage flags to set for the Allocation. The usage 1045 * flag {@link android.renderscript.Allocation#USAGE_IO_INPUT} will always 1046 * be set on the created Allocation, but additional flags may be provided 1047 * here. 1048 * @return a new YUV-type Allocation with dimensions equal to the current 1049 * preview size. 1050 * @throws RSIllegalArgumentException if the usage flags are not compatible 1051 * with an YUV Allocation. 1052 * @see #setPreviewCallbackAllocation 1053 * @hide 1054 */ 1055 public final Allocation createPreviewAllocation(RenderScript rs, int usage) 1056 throws RSIllegalArgumentException { 1057 Parameters p = getParameters(); 1058 Size previewSize = p.getPreviewSize(); 1059 Type.Builder yuvBuilder = new Type.Builder(rs, 1060 Element.createPixel(rs, 1061 Element.DataType.UNSIGNED_8, 1062 Element.DataKind.PIXEL_YUV)); 1063 // Use YV12 for wide compatibility. Changing this requires also 1064 // adjusting camera service's format selection. 1065 yuvBuilder.setYuvFormat(ImageFormat.YV12); 1066 yuvBuilder.setX(previewSize.width); 1067 yuvBuilder.setY(previewSize.height); 1068 1069 Allocation a = Allocation.createTyped(rs, yuvBuilder.create(), 1070 usage | Allocation.USAGE_IO_INPUT); 1071 1072 return a; 1073 } 1074 1075 /** 1076 * <p>Set an {@link android.renderscript.Allocation Allocation} as the 1077 * target of preview callback data. Use this method for efficient processing 1078 * of camera preview data with RenderScript. The Allocation must be created 1079 * with the {@link #createPreviewAllocation createPreviewAllocation } 1080 * method.</p> 1081 * 1082 * <p>Setting a preview allocation will disable any active preview callbacks 1083 * set by {@link #setPreviewCallback setPreviewCallback} or 1084 * {@link #setPreviewCallbackWithBuffer setPreviewCallbackWithBuffer}, and 1085 * vice versa. Using a preview allocation still requires an active standard 1086 * preview target to be set, either with 1087 * {@link #setPreviewTexture setPreviewTexture} or 1088 * {@link #setPreviewDisplay setPreviewDisplay}.</p> 1089 * 1090 * <p>To be notified when new frames are available to the Allocation, use 1091 * {@link android.renderscript.Allocation#setIoInputNotificationHandler Allocation.setIoInputNotificationHandler}. To 1092 * update the frame currently accessible from the Allocation to the latest 1093 * preview frame, call 1094 * {@link android.renderscript.Allocation#ioReceive Allocation.ioReceive}.</p> 1095 * 1096 * <p>To disable preview into the Allocation, call this method with a 1097 * {@code null} parameter.</p> 1098 * 1099 * <p>Once a preview allocation is set, the preview size set by 1100 * {@link Parameters#setPreviewSize setPreviewSize} cannot be changed. If 1101 * you wish to change the preview size, first remove the preview allocation 1102 * by calling {@code setPreviewCallbackAllocation(null)}, then change the 1103 * preview size, create a new preview Allocation with 1104 * {@link #createPreviewAllocation createPreviewAllocation}, and set it as 1105 * the new preview callback allocation target.</p> 1106 * 1107 * <p>If you are using the preview data to create video or still images, 1108 * strongly consider using {@link android.media.MediaActionSound} to 1109 * properly indicate image capture or recording start/stop to the user.</p> 1110 * 1111 * @param previewAllocation the allocation to use as destination for preview 1112 * @throws IOException if configuring the camera to use the Allocation for 1113 * preview fails. 1114 * @throws IllegalArgumentException if the Allocation's dimensions or other 1115 * parameters don't meet the requirements. 1116 * @see #createPreviewAllocation 1117 * @see #setPreviewCallback 1118 * @see #setPreviewCallbackWithBuffer 1119 * @hide 1120 */ 1121 public final void setPreviewCallbackAllocation(Allocation previewAllocation) 1122 throws IOException { 1123 Surface previewSurface = null; 1124 if (previewAllocation != null) { 1125 Parameters p = getParameters(); 1126 Size previewSize = p.getPreviewSize(); 1127 if (previewSize.width != previewAllocation.getType().getX() || 1128 previewSize.height != previewAllocation.getType().getY()) { 1129 throw new IllegalArgumentException( 1130 "Allocation dimensions don't match preview dimensions: " + 1131 "Allocation is " + 1132 previewAllocation.getType().getX() + 1133 ", " + 1134 previewAllocation.getType().getY() + 1135 ". Preview is " + previewSize.width + ", " + 1136 previewSize.height); 1137 } 1138 if ((previewAllocation.getUsage() & 1139 Allocation.USAGE_IO_INPUT) == 0) { 1140 throw new IllegalArgumentException( 1141 "Allocation usage does not include USAGE_IO_INPUT"); 1142 } 1143 if (previewAllocation.getType().getElement().getDataKind() != 1144 Element.DataKind.PIXEL_YUV) { 1145 throw new IllegalArgumentException( 1146 "Allocation is not of a YUV type"); 1147 } 1148 previewSurface = previewAllocation.getSurface(); 1149 mUsingPreviewAllocation = true; 1150 } else { 1151 mUsingPreviewAllocation = false; 1152 } 1153 setPreviewCallbackSurface(previewSurface); 1154 } 1155 1156 private native final void setPreviewCallbackSurface(Surface s); 1157 1158 private class EventHandler extends Handler 1159 { 1160 private final Camera mCamera; 1161 1162 public EventHandler(Camera c, Looper looper) { 1163 super(looper); 1164 mCamera = c; 1165 } 1166 1167 @Override 1168 public void handleMessage(Message msg) { 1169 switch(msg.what) { 1170 case CAMERA_MSG_SHUTTER: 1171 if (mShutterCallback != null) { 1172 mShutterCallback.onShutter(); 1173 } 1174 return; 1175 1176 case CAMERA_MSG_RAW_IMAGE: 1177 if (mRawImageCallback != null) { 1178 mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera); 1179 } 1180 return; 1181 1182 case CAMERA_MSG_COMPRESSED_IMAGE: 1183 if (mJpegCallback != null) { 1184 mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera); 1185 } 1186 return; 1187 1188 case CAMERA_MSG_PREVIEW_FRAME: 1189 PreviewCallback pCb = mPreviewCallback; 1190 if (pCb != null) { 1191 if (mOneShot) { 1192 // Clear the callback variable before the callback 1193 // in case the app calls setPreviewCallback from 1194 // the callback function 1195 mPreviewCallback = null; 1196 } else if (!mWithBuffer) { 1197 // We're faking the camera preview mode to prevent 1198 // the app from being flooded with preview frames. 1199 // Set to oneshot mode again. 1200 setHasPreviewCallback(true, false); 1201 } 1202 pCb.onPreviewFrame((byte[])msg.obj, mCamera); 1203 } 1204 return; 1205 1206 case CAMERA_MSG_POSTVIEW_FRAME: 1207 if (mPostviewCallback != null) { 1208 mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera); 1209 } 1210 return; 1211 1212 case CAMERA_MSG_FOCUS: 1213 AutoFocusCallback cb = null; 1214 synchronized (mAutoFocusCallbackLock) { 1215 cb = mAutoFocusCallback; 1216 } 1217 if (cb != null) { 1218 boolean success = msg.arg1 == 0 ? false : true; 1219 cb.onAutoFocus(success, mCamera); 1220 } 1221 return; 1222 1223 case CAMERA_MSG_ZOOM: 1224 if (mZoomListener != null) { 1225 mZoomListener.onZoomChange(msg.arg1, msg.arg2 != 0, mCamera); 1226 } 1227 return; 1228 1229 case CAMERA_MSG_PREVIEW_METADATA: 1230 if (mFaceListener != null) { 1231 mFaceListener.onFaceDetection((Face[])msg.obj, mCamera); 1232 } 1233 return; 1234 1235 case CAMERA_MSG_ERROR : 1236 Log.e(TAG, "Error " + msg.arg1); 1237 if (mErrorCallback != null) { 1238 mErrorCallback.onError(msg.arg1, mCamera); 1239 } 1240 return; 1241 1242 case CAMERA_MSG_FOCUS_MOVE: 1243 if (mAutoFocusMoveCallback != null) { 1244 mAutoFocusMoveCallback.onAutoFocusMoving(msg.arg1 == 0 ? false : true, mCamera); 1245 } 1246 return; 1247 1248 default: 1249 Log.e(TAG, "Unknown message type " + msg.what); 1250 return; 1251 } 1252 } 1253 } 1254 1255 private static void postEventFromNative(Object camera_ref, 1256 int what, int arg1, int arg2, Object obj) 1257 { 1258 Camera c = (Camera)((WeakReference)camera_ref).get(); 1259 if (c == null) 1260 return; 1261 1262 if (c.mEventHandler != null) { 1263 Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1264 c.mEventHandler.sendMessage(m); 1265 } 1266 } 1267 1268 /** 1269 * Callback interface used to notify on completion of camera auto focus. 1270 * 1271 * <p>Devices that do not support auto-focus will receive a "fake" 1272 * callback to this interface. If your application needs auto-focus and 1273 * should not be installed on devices <em>without</em> auto-focus, you must 1274 * declare that your app uses the 1275 * {@code android.hardware.camera.autofocus} feature, in the 1276 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 1277 * manifest element.</p> 1278 * 1279 * @see #autoFocus(AutoFocusCallback) 1280 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1281 * applications. 1282 */ 1283 @Deprecated 1284 public interface AutoFocusCallback 1285 { 1286 /** 1287 * Called when the camera auto focus completes. If the camera 1288 * does not support auto-focus and autoFocus is called, 1289 * onAutoFocus will be called immediately with a fake value of 1290 * <code>success</code> set to <code>true</code>. 1291 * 1292 * The auto-focus routine does not lock auto-exposure and auto-white 1293 * balance after it completes. 1294 * 1295 * @param success true if focus was successful, false if otherwise 1296 * @param camera the Camera service object 1297 * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean) 1298 * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean) 1299 */ 1300 void onAutoFocus(boolean success, Camera camera); 1301 } 1302 1303 /** 1304 * Starts camera auto-focus and registers a callback function to run when 1305 * the camera is focused. This method is only valid when preview is active 1306 * (between {@link #startPreview()} and before {@link #stopPreview()}). 1307 * 1308 * <p>Callers should check 1309 * {@link android.hardware.Camera.Parameters#getFocusMode()} to determine if 1310 * this method should be called. If the camera does not support auto-focus, 1311 * it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean, Camera)} 1312 * callback will be called immediately. 1313 * 1314 * <p>If your application should not be installed 1315 * on devices without auto-focus, you must declare that your application 1316 * uses auto-focus with the 1317 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 1318 * manifest element.</p> 1319 * 1320 * <p>If the current flash mode is not 1321 * {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be 1322 * fired during auto-focus, depending on the driver and camera hardware.<p> 1323 * 1324 * <p>Auto-exposure lock {@link android.hardware.Camera.Parameters#getAutoExposureLock()} 1325 * and auto-white balance locks {@link android.hardware.Camera.Parameters#getAutoWhiteBalanceLock()} 1326 * do not change during and after autofocus. But auto-focus routine may stop 1327 * auto-exposure and auto-white balance transiently during focusing. 1328 * 1329 * <p>Stopping preview with {@link #stopPreview()}, or triggering still 1330 * image capture with {@link #takePicture(Camera.ShutterCallback, 1331 * Camera.PictureCallback, Camera.PictureCallback)}, will not change the 1332 * the focus position. Applications must call cancelAutoFocus to reset the 1333 * focus.</p> 1334 * 1335 * <p>If autofocus is successful, consider using 1336 * {@link android.media.MediaActionSound} to properly play back an autofocus 1337 * success sound to the user.</p> 1338 * 1339 * @param cb the callback to run 1340 * @throws RuntimeException if starting autofocus fails; usually this would 1341 * be because of a hardware or other low-level error, or because 1342 * release() has been called on this Camera instance. 1343 * @see #cancelAutoFocus() 1344 * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean) 1345 * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean) 1346 * @see android.media.MediaActionSound 1347 */ 1348 public final void autoFocus(AutoFocusCallback cb) 1349 { 1350 synchronized (mAutoFocusCallbackLock) { 1351 mAutoFocusCallback = cb; 1352 } 1353 native_autoFocus(); 1354 } 1355 private native final void native_autoFocus(); 1356 1357 /** 1358 * Cancels any auto-focus function in progress. 1359 * Whether or not auto-focus is currently in progress, 1360 * this function will return the focus position to the default. 1361 * If the camera does not support auto-focus, this is a no-op. 1362 * 1363 * @throws RuntimeException if canceling autofocus fails; usually this would 1364 * be because of a hardware or other low-level error, or because 1365 * release() has been called on this Camera instance. 1366 * @see #autoFocus(Camera.AutoFocusCallback) 1367 */ 1368 public final void cancelAutoFocus() 1369 { 1370 synchronized (mAutoFocusCallbackLock) { 1371 mAutoFocusCallback = null; 1372 } 1373 native_cancelAutoFocus(); 1374 // CAMERA_MSG_FOCUS should be removed here because the following 1375 // scenario can happen: 1376 // - An application uses the same thread for autoFocus, cancelAutoFocus 1377 // and looper thread. 1378 // - The application calls autoFocus. 1379 // - HAL sends CAMERA_MSG_FOCUS, which enters the looper message queue. 1380 // Before event handler's handleMessage() is invoked, the application 1381 // calls cancelAutoFocus and autoFocus. 1382 // - The application gets the old CAMERA_MSG_FOCUS and thinks autofocus 1383 // has been completed. But in fact it is not. 1384 // 1385 // As documented in the beginning of the file, apps should not use 1386 // multiple threads to call autoFocus and cancelAutoFocus at the same 1387 // time. It is HAL's responsibility not to send a CAMERA_MSG_FOCUS 1388 // message after native_cancelAutoFocus is called. 1389 mEventHandler.removeMessages(CAMERA_MSG_FOCUS); 1390 } 1391 private native final void native_cancelAutoFocus(); 1392 1393 /** 1394 * Callback interface used to notify on auto focus start and stop. 1395 * 1396 * <p>This is only supported in continuous autofocus modes -- {@link 1397 * Parameters#FOCUS_MODE_CONTINUOUS_VIDEO} and {@link 1398 * Parameters#FOCUS_MODE_CONTINUOUS_PICTURE}. Applications can show 1399 * autofocus animation based on this.</p> 1400 * 1401 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1402 * applications. 1403 */ 1404 @Deprecated 1405 public interface AutoFocusMoveCallback 1406 { 1407 /** 1408 * Called when the camera auto focus starts or stops. 1409 * 1410 * @param start true if focus starts to move, false if focus stops to move 1411 * @param camera the Camera service object 1412 */ 1413 void onAutoFocusMoving(boolean start, Camera camera); 1414 } 1415 1416 /** 1417 * Sets camera auto-focus move callback. 1418 * 1419 * @param cb the callback to run 1420 * @throws RuntimeException if enabling the focus move callback fails; 1421 * usually this would be because of a hardware or other low-level error, 1422 * or because release() has been called on this Camera instance. 1423 */ 1424 public void setAutoFocusMoveCallback(AutoFocusMoveCallback cb) { 1425 mAutoFocusMoveCallback = cb; 1426 enableFocusMoveCallback((mAutoFocusMoveCallback != null) ? 1 : 0); 1427 } 1428 1429 private native void enableFocusMoveCallback(int enable); 1430 1431 /** 1432 * Callback interface used to signal the moment of actual image capture. 1433 * 1434 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 1435 * 1436 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1437 * applications. 1438 */ 1439 @Deprecated 1440 public interface ShutterCallback 1441 { 1442 /** 1443 * Called as near as possible to the moment when a photo is captured 1444 * from the sensor. This is a good opportunity to play a shutter sound 1445 * or give other feedback of camera operation. This may be some time 1446 * after the photo was triggered, but some time before the actual data 1447 * is available. 1448 */ 1449 void onShutter(); 1450 } 1451 1452 /** 1453 * Callback interface used to supply image data from a photo capture. 1454 * 1455 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 1456 * 1457 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1458 * applications. 1459 */ 1460 @Deprecated 1461 public interface PictureCallback { 1462 /** 1463 * Called when image data is available after a picture is taken. 1464 * The format of the data depends on the context of the callback 1465 * and {@link Camera.Parameters} settings. 1466 * 1467 * @param data a byte array of the picture data 1468 * @param camera the Camera service object 1469 */ 1470 void onPictureTaken(byte[] data, Camera camera); 1471 }; 1472 1473 /** 1474 * Equivalent to <pre>takePicture(Shutter, raw, null, jpeg)</pre>. 1475 * 1476 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 1477 */ 1478 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 1479 PictureCallback jpeg) { 1480 takePicture(shutter, raw, null, jpeg); 1481 } 1482 private native final void native_takePicture(int msgType); 1483 1484 /** 1485 * Triggers an asynchronous image capture. The camera service will initiate 1486 * a series of callbacks to the application as the image capture progresses. 1487 * The shutter callback occurs after the image is captured. This can be used 1488 * to trigger a sound to let the user know that image has been captured. The 1489 * raw callback occurs when the raw image data is available (NOTE: the data 1490 * will be null if there is no raw image callback buffer available or the 1491 * raw image callback buffer is not large enough to hold the raw image). 1492 * The postview callback occurs when a scaled, fully processed postview 1493 * image is available (NOTE: not all hardware supports this). The jpeg 1494 * callback occurs when the compressed image is available. If the 1495 * application does not need a particular callback, a null can be passed 1496 * instead of a callback method. 1497 * 1498 * <p>This method is only valid when preview is active (after 1499 * {@link #startPreview()}). Preview will be stopped after the image is 1500 * taken; callers must call {@link #startPreview()} again if they want to 1501 * re-start preview or take more pictures. This should not be called between 1502 * {@link android.media.MediaRecorder#start()} and 1503 * {@link android.media.MediaRecorder#stop()}. 1504 * 1505 * <p>After calling this method, you must not call {@link #startPreview()} 1506 * or take another picture until the JPEG callback has returned. 1507 * 1508 * @param shutter the callback for image capture moment, or null 1509 * @param raw the callback for raw (uncompressed) image data, or null 1510 * @param postview callback with postview image data, may be null 1511 * @param jpeg the callback for JPEG image data, or null 1512 * @throws RuntimeException if starting picture capture fails; usually this 1513 * would be because of a hardware or other low-level error, or because 1514 * release() has been called on this Camera instance. 1515 */ 1516 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 1517 PictureCallback postview, PictureCallback jpeg) { 1518 mShutterCallback = shutter; 1519 mRawImageCallback = raw; 1520 mPostviewCallback = postview; 1521 mJpegCallback = jpeg; 1522 1523 // If callback is not set, do not send me callbacks. 1524 int msgType = 0; 1525 if (mShutterCallback != null) { 1526 msgType |= CAMERA_MSG_SHUTTER; 1527 } 1528 if (mRawImageCallback != null) { 1529 msgType |= CAMERA_MSG_RAW_IMAGE; 1530 } 1531 if (mPostviewCallback != null) { 1532 msgType |= CAMERA_MSG_POSTVIEW_FRAME; 1533 } 1534 if (mJpegCallback != null) { 1535 msgType |= CAMERA_MSG_COMPRESSED_IMAGE; 1536 } 1537 1538 native_takePicture(msgType); 1539 mFaceDetectionRunning = false; 1540 } 1541 1542 /** 1543 * Zooms to the requested value smoothly. The driver will notify {@link 1544 * OnZoomChangeListener} of the zoom value and whether zoom is stopped at 1545 * the time. For example, suppose the current zoom is 0 and startSmoothZoom 1546 * is called with value 3. The 1547 * {@link Camera.OnZoomChangeListener#onZoomChange(int, boolean, Camera)} 1548 * method will be called three times with zoom values 1, 2, and 3. 1549 * Applications can call {@link #stopSmoothZoom} to stop the zoom earlier. 1550 * Applications should not call startSmoothZoom again or change the zoom 1551 * value before zoom stops. If the supplied zoom value equals to the current 1552 * zoom value, no zoom callback will be generated. This method is supported 1553 * if {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} 1554 * returns true. 1555 * 1556 * @param value zoom value. The valid range is 0 to {@link 1557 * android.hardware.Camera.Parameters#getMaxZoom}. 1558 * @throws IllegalArgumentException if the zoom value is invalid. 1559 * @throws RuntimeException if the method fails. 1560 * @see #setZoomChangeListener(OnZoomChangeListener) 1561 */ 1562 public native final void startSmoothZoom(int value); 1563 1564 /** 1565 * Stops the smooth zoom. Applications should wait for the {@link 1566 * OnZoomChangeListener} to know when the zoom is actually stopped. This 1567 * method is supported if {@link 1568 * android.hardware.Camera.Parameters#isSmoothZoomSupported} is true. 1569 * 1570 * @throws RuntimeException if the method fails. 1571 */ 1572 public native final void stopSmoothZoom(); 1573 1574 /** 1575 * Set the clockwise rotation of preview display in degrees. This affects 1576 * the preview frames and the picture displayed after snapshot. This method 1577 * is useful for portrait mode applications. Note that preview display of 1578 * front-facing cameras is flipped horizontally before the rotation, that 1579 * is, the image is reflected along the central vertical axis of the camera 1580 * sensor. So the users can see themselves as looking into a mirror. 1581 * 1582 * <p>This does not affect the order of byte array passed in {@link 1583 * PreviewCallback#onPreviewFrame}, JPEG pictures, or recorded videos. This 1584 * method is not allowed to be called during preview. 1585 * 1586 * <p>If you want to make the camera image show in the same orientation as 1587 * the display, you can use the following code. 1588 * <pre> 1589 * public static void setCameraDisplayOrientation(Activity activity, 1590 * int cameraId, android.hardware.Camera camera) { 1591 * android.hardware.Camera.CameraInfo info = 1592 * new android.hardware.Camera.CameraInfo(); 1593 * android.hardware.Camera.getCameraInfo(cameraId, info); 1594 * int rotation = activity.getWindowManager().getDefaultDisplay() 1595 * .getRotation(); 1596 * int degrees = 0; 1597 * switch (rotation) { 1598 * case Surface.ROTATION_0: degrees = 0; break; 1599 * case Surface.ROTATION_90: degrees = 90; break; 1600 * case Surface.ROTATION_180: degrees = 180; break; 1601 * case Surface.ROTATION_270: degrees = 270; break; 1602 * } 1603 * 1604 * int result; 1605 * if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 1606 * result = (info.orientation + degrees) % 360; 1607 * result = (360 - result) % 360; // compensate the mirror 1608 * } else { // back-facing 1609 * result = (info.orientation - degrees + 360) % 360; 1610 * } 1611 * camera.setDisplayOrientation(result); 1612 * } 1613 * </pre> 1614 * 1615 * <p>Starting from API level 14, this method can be called when preview is 1616 * active. 1617 * 1618 * <p><b>Note: </b>Before API level 24, the default value for orientation is 0. Starting in 1619 * API level 24, the default orientation will be such that applications in forced-landscape mode 1620 * will have correct preview orientation, which may be either a default of 0 or 1621 * 180. Applications that operate in portrait mode or allow for changing orientation must still 1622 * call this method after each orientation change to ensure correct preview display in all 1623 * cases.</p> 1624 * 1625 * @param degrees the angle that the picture will be rotated clockwise. 1626 * Valid values are 0, 90, 180, and 270. 1627 * @throws RuntimeException if setting orientation fails; usually this would 1628 * be because of a hardware or other low-level error, or because 1629 * release() has been called on this Camera instance. 1630 * @see #setPreviewDisplay(SurfaceHolder) 1631 */ 1632 public native final void setDisplayOrientation(int degrees); 1633 1634 /** 1635 * <p>Enable or disable the default shutter sound when taking a picture.</p> 1636 * 1637 * <p>By default, the camera plays the system-defined camera shutter sound 1638 * when {@link #takePicture} is called. Using this method, the shutter sound 1639 * can be disabled. It is strongly recommended that an alternative shutter 1640 * sound is played in the {@link ShutterCallback} when the system shutter 1641 * sound is disabled.</p> 1642 * 1643 * <p>Note that devices may not always allow disabling the camera shutter 1644 * sound. If the shutter sound state cannot be set to the desired value, 1645 * this method will return false. {@link CameraInfo#canDisableShutterSound} 1646 * can be used to determine whether the device will allow the shutter sound 1647 * to be disabled.</p> 1648 * 1649 * @param enabled whether the camera should play the system shutter sound 1650 * when {@link #takePicture takePicture} is called. 1651 * @return {@code true} if the shutter sound state was successfully 1652 * changed. {@code false} if the shutter sound state could not be 1653 * changed. {@code true} is also returned if shutter sound playback 1654 * is already set to the requested state. 1655 * @throws RuntimeException if the call fails; usually this would be because 1656 * of a hardware or other low-level error, or because release() has been 1657 * called on this Camera instance. 1658 * @see #takePicture 1659 * @see CameraInfo#canDisableShutterSound 1660 * @see ShutterCallback 1661 */ 1662 public final boolean enableShutterSound(boolean enabled) { 1663 if (!enabled) { 1664 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE); 1665 IAudioService audioService = IAudioService.Stub.asInterface(b); 1666 try { 1667 if (audioService.isCameraSoundForced()) return false; 1668 } catch (RemoteException e) { 1669 Log.e(TAG, "Audio service is unavailable for queries"); 1670 } 1671 } 1672 synchronized (mShutterSoundLock) { 1673 if (enabled && mHasAppOpsPlayAudio) { 1674 Log.i(TAG, "Shutter sound is not allowed by AppOpsManager"); 1675 return false; 1676 } 1677 boolean ret = _enableShutterSound(enabled); 1678 if (ret) { 1679 mShutterSoundEnabledFromApp = enabled; 1680 } 1681 return ret; 1682 } 1683 } 1684 1685 /** 1686 * Disable the shutter sound unconditionally. 1687 * 1688 * <p> 1689 * This is only guaranteed to work for legacy cameras 1690 * (i.e. initialized with {@link #cameraInitUnspecified}). Trying to call this on 1691 * a regular camera will force a conditional check in the camera service. 1692 * </p> 1693 * 1694 * @return {@code true} if the shutter sound state was successfully 1695 * changed. {@code false} if the shutter sound state could not be 1696 * changed. {@code true} is also returned if shutter sound playback 1697 * is already set to the requested state. 1698 * 1699 * @hide 1700 */ 1701 public final boolean disableShutterSound() { 1702 return _enableShutterSound(/*enabled*/false); 1703 } 1704 1705 private native final boolean _enableShutterSound(boolean enabled); 1706 1707 private static class IAppOpsCallbackWrapper extends IAppOpsCallback.Stub { 1708 private final WeakReference<Camera> mWeakCamera; 1709 1710 IAppOpsCallbackWrapper(Camera camera) { 1711 mWeakCamera = new WeakReference<Camera>(camera); 1712 } 1713 1714 @Override 1715 public void opChanged(int op, int uid, String packageName) { 1716 if (op == AppOpsManager.OP_PLAY_AUDIO) { 1717 final Camera camera = mWeakCamera.get(); 1718 if (camera != null) { 1719 camera.updateAppOpsPlayAudio(); 1720 } 1721 } 1722 } 1723 } 1724 1725 private void updateAppOpsPlayAudio() { 1726 synchronized (mShutterSoundLock) { 1727 boolean oldHasAppOpsPlayAudio = mHasAppOpsPlayAudio; 1728 try { 1729 int mode = AppOpsManager.MODE_IGNORED; 1730 if (mAppOps != null) { 1731 mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO, 1732 AudioAttributes.USAGE_ASSISTANCE_SONIFICATION, 1733 Process.myUid(), ActivityThread.currentPackageName()); 1734 } 1735 mHasAppOpsPlayAudio = mode == AppOpsManager.MODE_ALLOWED; 1736 } catch (RemoteException e) { 1737 Log.e(TAG, "AppOpsService check audio operation failed"); 1738 mHasAppOpsPlayAudio = false; 1739 } 1740 if (oldHasAppOpsPlayAudio != mHasAppOpsPlayAudio) { 1741 if (!mHasAppOpsPlayAudio) { 1742 _enableShutterSound(false); 1743 } else { 1744 _enableShutterSound(mShutterSoundEnabledFromApp); 1745 } 1746 } 1747 } 1748 } 1749 1750 /** 1751 * Callback interface for zoom changes during a smooth zoom operation. 1752 * 1753 * @see #setZoomChangeListener(OnZoomChangeListener) 1754 * @see #startSmoothZoom(int) 1755 * 1756 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1757 * applications. 1758 */ 1759 @Deprecated 1760 public interface OnZoomChangeListener 1761 { 1762 /** 1763 * Called when the zoom value has changed during a smooth zoom. 1764 * 1765 * @param zoomValue the current zoom value. In smooth zoom mode, camera 1766 * calls this for every new zoom value. 1767 * @param stopped whether smooth zoom is stopped. If the value is true, 1768 * this is the last zoom update for the application. 1769 * @param camera the Camera service object 1770 */ 1771 void onZoomChange(int zoomValue, boolean stopped, Camera camera); 1772 }; 1773 1774 /** 1775 * Registers a listener to be notified when the zoom value is updated by the 1776 * camera driver during smooth zoom. 1777 * 1778 * @param listener the listener to notify 1779 * @see #startSmoothZoom(int) 1780 */ 1781 public final void setZoomChangeListener(OnZoomChangeListener listener) 1782 { 1783 mZoomListener = listener; 1784 } 1785 1786 /** 1787 * Callback interface for face detected in the preview frame. 1788 * 1789 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1790 * applications. 1791 */ 1792 @Deprecated 1793 public interface FaceDetectionListener 1794 { 1795 /** 1796 * Notify the listener of the detected faces in the preview frame. 1797 * 1798 * @param faces The detected faces in a list 1799 * @param camera The {@link Camera} service object 1800 */ 1801 void onFaceDetection(Face[] faces, Camera camera); 1802 } 1803 1804 /** 1805 * Registers a listener to be notified about the faces detected in the 1806 * preview frame. 1807 * 1808 * @param listener the listener to notify 1809 * @see #startFaceDetection() 1810 */ 1811 public final void setFaceDetectionListener(FaceDetectionListener listener) 1812 { 1813 mFaceListener = listener; 1814 } 1815 1816 /** 1817 * Starts the face detection. This should be called after preview is started. 1818 * The camera will notify {@link FaceDetectionListener} of the detected 1819 * faces in the preview frame. The detected faces may be the same as the 1820 * previous ones. Applications should call {@link #stopFaceDetection} to 1821 * stop the face detection. This method is supported if {@link 1822 * Parameters#getMaxNumDetectedFaces()} returns a number larger than 0. 1823 * If the face detection has started, apps should not call this again. 1824 * 1825 * <p>When the face detection is running, {@link Parameters#setWhiteBalance(String)}, 1826 * {@link Parameters#setFocusAreas(List)}, and {@link Parameters#setMeteringAreas(List)} 1827 * have no effect. The camera uses the detected faces to do auto-white balance, 1828 * auto exposure, and autofocus. 1829 * 1830 * <p>If the apps call {@link #autoFocus(AutoFocusCallback)}, the camera 1831 * will stop sending face callbacks. The last face callback indicates the 1832 * areas used to do autofocus. After focus completes, face detection will 1833 * resume sending face callbacks. If the apps call {@link 1834 * #cancelAutoFocus()}, the face callbacks will also resume.</p> 1835 * 1836 * <p>After calling {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, 1837 * Camera.PictureCallback)} or {@link #stopPreview()}, and then resuming 1838 * preview with {@link #startPreview()}, the apps should call this method 1839 * again to resume face detection.</p> 1840 * 1841 * @throws IllegalArgumentException if the face detection is unsupported. 1842 * @throws RuntimeException if the method fails or the face detection is 1843 * already running. 1844 * @see FaceDetectionListener 1845 * @see #stopFaceDetection() 1846 * @see Parameters#getMaxNumDetectedFaces() 1847 */ 1848 public final void startFaceDetection() { 1849 if (mFaceDetectionRunning) { 1850 throw new RuntimeException("Face detection is already running"); 1851 } 1852 _startFaceDetection(CAMERA_FACE_DETECTION_HW); 1853 mFaceDetectionRunning = true; 1854 } 1855 1856 /** 1857 * Stops the face detection. 1858 * 1859 * @see #startFaceDetection() 1860 */ 1861 public final void stopFaceDetection() { 1862 _stopFaceDetection(); 1863 mFaceDetectionRunning = false; 1864 } 1865 1866 private native final void _startFaceDetection(int type); 1867 private native final void _stopFaceDetection(); 1868 1869 /** 1870 * Information about a face identified through camera face detection. 1871 * 1872 * <p>When face detection is used with a camera, the {@link FaceDetectionListener} returns a 1873 * list of face objects for use in focusing and metering.</p> 1874 * 1875 * @see FaceDetectionListener 1876 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1877 * applications. 1878 */ 1879 @Deprecated 1880 public static class Face { 1881 /** 1882 * Create an empty face. 1883 */ 1884 public Face() { 1885 } 1886 1887 /** 1888 * Bounds of the face. (-1000, -1000) represents the top-left of the 1889 * camera field of view, and (1000, 1000) represents the bottom-right of 1890 * the field of view. For example, suppose the size of the viewfinder UI 1891 * is 800x480. The rect passed from the driver is (-1000, -1000, 0, 0). 1892 * The corresponding viewfinder rect should be (0, 0, 400, 240). It is 1893 * guaranteed left < right and top < bottom. The coordinates can be 1894 * smaller than -1000 or bigger than 1000. But at least one vertex will 1895 * be within (-1000, -1000) and (1000, 1000). 1896 * 1897 * <p>The direction is relative to the sensor orientation, that is, what 1898 * the sensor sees. The direction is not affected by the rotation or 1899 * mirroring of {@link #setDisplayOrientation(int)}. The face bounding 1900 * rectangle does not provide any information about face orientation.</p> 1901 * 1902 * <p>Here is the matrix to convert driver coordinates to View coordinates 1903 * in pixels.</p> 1904 * <pre> 1905 * Matrix matrix = new Matrix(); 1906 * CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId]; 1907 * // Need mirror for front camera. 1908 * boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); 1909 * matrix.setScale(mirror ? -1 : 1, 1); 1910 * // This is the value for android.hardware.Camera.setDisplayOrientation. 1911 * matrix.postRotate(displayOrientation); 1912 * // Camera driver coordinates range from (-1000, -1000) to (1000, 1000). 1913 * // UI coordinates range from (0, 0) to (width, height). 1914 * matrix.postScale(view.getWidth() / 2000f, view.getHeight() / 2000f); 1915 * matrix.postTranslate(view.getWidth() / 2f, view.getHeight() / 2f); 1916 * </pre> 1917 * 1918 * @see #startFaceDetection() 1919 */ 1920 public Rect rect; 1921 1922 /** 1923 * <p>The confidence level for the detection of the face. The range is 1 to 1924 * 100. 100 is the highest confidence.</p> 1925 * 1926 * <p>Depending on the device, even very low-confidence faces may be 1927 * listed, so applications should filter out faces with low confidence, 1928 * depending on the use case. For a typical point-and-shoot camera 1929 * application that wishes to display rectangles around detected faces, 1930 * filtering out faces with confidence less than 50 is recommended.</p> 1931 * 1932 * @see #startFaceDetection() 1933 */ 1934 public int score; 1935 1936 /** 1937 * An unique id per face while the face is visible to the tracker. If 1938 * the face leaves the field-of-view and comes back, it will get a new 1939 * id. This is an optional field, may not be supported on all devices. 1940 * If not supported, id will always be set to -1. The optional fields 1941 * are supported as a set. Either they are all valid, or none of them 1942 * are. 1943 */ 1944 public int id = -1; 1945 1946 /** 1947 * The coordinates of the center of the left eye. The coordinates are in 1948 * the same space as the ones for {@link #rect}. This is an optional 1949 * field, may not be supported on all devices. If not supported, the 1950 * value will always be set to null. The optional fields are supported 1951 * as a set. Either they are all valid, or none of them are. 1952 */ 1953 public Point leftEye = null; 1954 1955 /** 1956 * The coordinates of the center of the right eye. The coordinates are 1957 * in the same space as the ones for {@link #rect}.This is an optional 1958 * field, may not be supported on all devices. If not supported, the 1959 * value will always be set to null. The optional fields are supported 1960 * as a set. Either they are all valid, or none of them are. 1961 */ 1962 public Point rightEye = null; 1963 1964 /** 1965 * The coordinates of the center of the mouth. The coordinates are in 1966 * the same space as the ones for {@link #rect}. This is an optional 1967 * field, may not be supported on all devices. If not supported, the 1968 * value will always be set to null. The optional fields are supported 1969 * as a set. Either they are all valid, or none of them are. 1970 */ 1971 public Point mouth = null; 1972 } 1973 1974 /** 1975 * Unspecified camera error. 1976 * @see Camera.ErrorCallback 1977 */ 1978 public static final int CAMERA_ERROR_UNKNOWN = 1; 1979 1980 /** 1981 * Camera was disconnected due to use by higher priority user. 1982 * @see Camera.ErrorCallback 1983 */ 1984 public static final int CAMERA_ERROR_EVICTED = 2; 1985 1986 /** 1987 * Media server died. In this case, the application must release the 1988 * Camera object and instantiate a new one. 1989 * @see Camera.ErrorCallback 1990 */ 1991 public static final int CAMERA_ERROR_SERVER_DIED = 100; 1992 1993 /** 1994 * Callback interface for camera error notification. 1995 * 1996 * @see #setErrorCallback(ErrorCallback) 1997 * 1998 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1999 * applications. 2000 */ 2001 @Deprecated 2002 public interface ErrorCallback 2003 { 2004 /** 2005 * Callback for camera errors. 2006 * @param error error code: 2007 * <ul> 2008 * <li>{@link #CAMERA_ERROR_UNKNOWN} 2009 * <li>{@link #CAMERA_ERROR_SERVER_DIED} 2010 * </ul> 2011 * @param camera the Camera service object 2012 */ 2013 void onError(int error, Camera camera); 2014 }; 2015 2016 /** 2017 * Registers a callback to be invoked when an error occurs. 2018 * @param cb The callback to run 2019 */ 2020 public final void setErrorCallback(ErrorCallback cb) 2021 { 2022 mErrorCallback = cb; 2023 } 2024 2025 private native final void native_setParameters(String params); 2026 private native final String native_getParameters(); 2027 2028 /** 2029 * Changes the settings for this Camera service. 2030 * 2031 * @param params the Parameters to use for this Camera service 2032 * @throws RuntimeException if any parameter is invalid or not supported. 2033 * @see #getParameters() 2034 */ 2035 public void setParameters(Parameters params) { 2036 // If using preview allocations, don't allow preview size changes 2037 if (mUsingPreviewAllocation) { 2038 Size newPreviewSize = params.getPreviewSize(); 2039 Size currentPreviewSize = getParameters().getPreviewSize(); 2040 if (newPreviewSize.width != currentPreviewSize.width || 2041 newPreviewSize.height != currentPreviewSize.height) { 2042 throw new IllegalStateException("Cannot change preview size" + 2043 " while a preview allocation is configured."); 2044 } 2045 } 2046 2047 native_setParameters(params.flatten()); 2048 } 2049 2050 /** 2051 * Returns the current settings for this Camera service. 2052 * If modifications are made to the returned Parameters, they must be passed 2053 * to {@link #setParameters(Camera.Parameters)} to take effect. 2054 * 2055 * @throws RuntimeException if reading parameters fails; usually this would 2056 * be because of a hardware or other low-level error, or because 2057 * release() has been called on this Camera instance. 2058 * @see #setParameters(Camera.Parameters) 2059 */ 2060 public Parameters getParameters() { 2061 Parameters p = new Parameters(); 2062 String s = native_getParameters(); 2063 p.unflatten(s); 2064 return p; 2065 } 2066 2067 /** 2068 * Returns an empty {@link Parameters} for testing purpose. 2069 * 2070 * @return a Parameter object. 2071 * 2072 * @hide 2073 */ 2074 public static Parameters getEmptyParameters() { 2075 Camera camera = new Camera(); 2076 return camera.new Parameters(); 2077 } 2078 2079 /** 2080 * Returns a copied {@link Parameters}; for shim use only. 2081 * 2082 * @param parameters a non-{@code null} parameters 2083 * @return a Parameter object, with all the parameters copied from {@code parameters}. 2084 * 2085 * @throws NullPointerException if {@code parameters} was {@code null} 2086 * @hide 2087 */ 2088 public static Parameters getParametersCopy(Camera.Parameters parameters) { 2089 if (parameters == null) { 2090 throw new NullPointerException("parameters must not be null"); 2091 } 2092 2093 Camera camera = parameters.getOuter(); 2094 Parameters p = camera.new Parameters(); 2095 p.copyFrom(parameters); 2096 2097 return p; 2098 } 2099 2100 /** 2101 * Image size (width and height dimensions). 2102 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 2103 * applications. 2104 */ 2105 @Deprecated 2106 public class Size { 2107 /** 2108 * Sets the dimensions for pictures. 2109 * 2110 * @param w the photo width (pixels) 2111 * @param h the photo height (pixels) 2112 */ 2113 public Size(int w, int h) { 2114 width = w; 2115 height = h; 2116 } 2117 /** 2118 * Compares {@code obj} to this size. 2119 * 2120 * @param obj the object to compare this size with. 2121 * @return {@code true} if the width and height of {@code obj} is the 2122 * same as those of this size. {@code false} otherwise. 2123 */ 2124 @Override 2125 public boolean equals(Object obj) { 2126 if (!(obj instanceof Size)) { 2127 return false; 2128 } 2129 Size s = (Size) obj; 2130 return width == s.width && height == s.height; 2131 } 2132 @Override 2133 public int hashCode() { 2134 return width * 32713 + height; 2135 } 2136 /** width of the picture */ 2137 public int width; 2138 /** height of the picture */ 2139 public int height; 2140 }; 2141 2142 /** 2143 * <p>The Area class is used for choosing specific metering and focus areas for 2144 * the camera to use when calculating auto-exposure, auto-white balance, and 2145 * auto-focus.</p> 2146 * 2147 * <p>To find out how many simultaneous areas a given camera supports, use 2148 * {@link Parameters#getMaxNumMeteringAreas()} and 2149 * {@link Parameters#getMaxNumFocusAreas()}. If metering or focusing area 2150 * selection is unsupported, these methods will return 0.</p> 2151 * 2152 * <p>Each Area consists of a rectangle specifying its bounds, and a weight 2153 * that determines its importance. The bounds are relative to the camera's 2154 * current field of view. The coordinates are mapped so that (-1000, -1000) 2155 * is always the top-left corner of the current field of view, and (1000, 2156 * 1000) is always the bottom-right corner of the current field of 2157 * view. Setting Areas with bounds outside that range is not allowed. Areas 2158 * with zero or negative width or height are not allowed.</p> 2159 * 2160 * <p>The weight must range from 1 to 1000, and represents a weight for 2161 * every pixel in the area. This means that a large metering area with 2162 * the same weight as a smaller area will have more effect in the 2163 * metering result. Metering areas can overlap and the driver 2164 * will add the weights in the overlap region.</p> 2165 * 2166 * @see Parameters#setFocusAreas(List) 2167 * @see Parameters#getFocusAreas() 2168 * @see Parameters#getMaxNumFocusAreas() 2169 * @see Parameters#setMeteringAreas(List) 2170 * @see Parameters#getMeteringAreas() 2171 * @see Parameters#getMaxNumMeteringAreas() 2172 * 2173 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 2174 * applications. 2175 */ 2176 @Deprecated 2177 public static class Area { 2178 /** 2179 * Create an area with specified rectangle and weight. 2180 * 2181 * @param rect the bounds of the area. 2182 * @param weight the weight of the area. 2183 */ 2184 public Area(Rect rect, int weight) { 2185 this.rect = rect; 2186 this.weight = weight; 2187 } 2188 /** 2189 * Compares {@code obj} to this area. 2190 * 2191 * @param obj the object to compare this area with. 2192 * @return {@code true} if the rectangle and weight of {@code obj} is 2193 * the same as those of this area. {@code false} otherwise. 2194 */ 2195 @Override 2196 public boolean equals(Object obj) { 2197 if (!(obj instanceof Area)) { 2198 return false; 2199 } 2200 Area a = (Area) obj; 2201 if (rect == null) { 2202 if (a.rect != null) return false; 2203 } else { 2204 if (!rect.equals(a.rect)) return false; 2205 } 2206 return weight == a.weight; 2207 } 2208 2209 /** 2210 * Bounds of the area. (-1000, -1000) represents the top-left of the 2211 * camera field of view, and (1000, 1000) represents the bottom-right of 2212 * the field of view. Setting bounds outside that range is not 2213 * allowed. Bounds with zero or negative width or height are not 2214 * allowed. 2215 * 2216 * @see Parameters#getFocusAreas() 2217 * @see Parameters#getMeteringAreas() 2218 */ 2219 public Rect rect; 2220 2221 /** 2222 * Weight of the area. The weight must range from 1 to 1000, and 2223 * represents a weight for every pixel in the area. This means that a 2224 * large metering area with the same weight as a smaller area will have 2225 * more effect in the metering result. Metering areas can overlap and 2226 * the driver will add the weights in the overlap region. 2227 * 2228 * @see Parameters#getFocusAreas() 2229 * @see Parameters#getMeteringAreas() 2230 */ 2231 public int weight; 2232 } 2233 2234 /** 2235 * Camera service settings. 2236 * 2237 * <p>To make camera parameters take effect, applications have to call 2238 * {@link Camera#setParameters(Camera.Parameters)}. For example, after 2239 * {@link Camera.Parameters#setWhiteBalance} is called, white balance is not 2240 * actually changed until {@link Camera#setParameters(Camera.Parameters)} 2241 * is called with the changed parameters object. 2242 * 2243 * <p>Different devices may have different camera capabilities, such as 2244 * picture size or flash modes. The application should query the camera 2245 * capabilities before setting parameters. For example, the application 2246 * should call {@link Camera.Parameters#getSupportedColorEffects()} before 2247 * calling {@link Camera.Parameters#setColorEffect(String)}. If the 2248 * camera does not support color effects, 2249 * {@link Camera.Parameters#getSupportedColorEffects()} will return null. 2250 * 2251 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 2252 * applications. 2253 */ 2254 @Deprecated 2255 public class Parameters { 2256 // Parameter keys to communicate with the camera driver. 2257 private static final String KEY_PREVIEW_SIZE = "preview-size"; 2258 private static final String KEY_PREVIEW_FORMAT = "preview-format"; 2259 private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate"; 2260 private static final String KEY_PREVIEW_FPS_RANGE = "preview-fps-range"; 2261 private static final String KEY_PICTURE_SIZE = "picture-size"; 2262 private static final String KEY_PICTURE_FORMAT = "picture-format"; 2263 private static final String KEY_JPEG_THUMBNAIL_SIZE = "jpeg-thumbnail-size"; 2264 private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width"; 2265 private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height"; 2266 private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality"; 2267 private static final String KEY_JPEG_QUALITY = "jpeg-quality"; 2268 private static final String KEY_ROTATION = "rotation"; 2269 private static final String KEY_GPS_LATITUDE = "gps-latitude"; 2270 private static final String KEY_GPS_LONGITUDE = "gps-longitude"; 2271 private static final String KEY_GPS_ALTITUDE = "gps-altitude"; 2272 private static final String KEY_GPS_TIMESTAMP = "gps-timestamp"; 2273 private static final String KEY_GPS_PROCESSING_METHOD = "gps-processing-method"; 2274 private static final String KEY_WHITE_BALANCE = "whitebalance"; 2275 private static final String KEY_EFFECT = "effect"; 2276 private static final String KEY_ANTIBANDING = "antibanding"; 2277 private static final String KEY_SCENE_MODE = "scene-mode"; 2278 private static final String KEY_FLASH_MODE = "flash-mode"; 2279 private static final String KEY_FOCUS_MODE = "focus-mode"; 2280 private static final String KEY_FOCUS_AREAS = "focus-areas"; 2281 private static final String KEY_MAX_NUM_FOCUS_AREAS = "max-num-focus-areas"; 2282 private static final String KEY_FOCAL_LENGTH = "focal-length"; 2283 private static final String KEY_HORIZONTAL_VIEW_ANGLE = "horizontal-view-angle"; 2284 private static final String KEY_VERTICAL_VIEW_ANGLE = "vertical-view-angle"; 2285 private static final String KEY_EXPOSURE_COMPENSATION = "exposure-compensation"; 2286 private static final String KEY_MAX_EXPOSURE_COMPENSATION = "max-exposure-compensation"; 2287 private static final String KEY_MIN_EXPOSURE_COMPENSATION = "min-exposure-compensation"; 2288 private static final String KEY_EXPOSURE_COMPENSATION_STEP = "exposure-compensation-step"; 2289 private static final String KEY_AUTO_EXPOSURE_LOCK = "auto-exposure-lock"; 2290 private static final String KEY_AUTO_EXPOSURE_LOCK_SUPPORTED = "auto-exposure-lock-supported"; 2291 private static final String KEY_AUTO_WHITEBALANCE_LOCK = "auto-whitebalance-lock"; 2292 private static final String KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED = "auto-whitebalance-lock-supported"; 2293 private static final String KEY_METERING_AREAS = "metering-areas"; 2294 private static final String KEY_MAX_NUM_METERING_AREAS = "max-num-metering-areas"; 2295 private static final String KEY_ZOOM = "zoom"; 2296 private static final String KEY_MAX_ZOOM = "max-zoom"; 2297 private static final String KEY_ZOOM_RATIOS = "zoom-ratios"; 2298 private static final String KEY_ZOOM_SUPPORTED = "zoom-supported"; 2299 private static final String KEY_SMOOTH_ZOOM_SUPPORTED = "smooth-zoom-supported"; 2300 private static final String KEY_FOCUS_DISTANCES = "focus-distances"; 2301 private static final String KEY_VIDEO_SIZE = "video-size"; 2302 private static final String KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO = 2303 "preferred-preview-size-for-video"; 2304 private static final String KEY_MAX_NUM_DETECTED_FACES_HW = "max-num-detected-faces-hw"; 2305 private static final String KEY_MAX_NUM_DETECTED_FACES_SW = "max-num-detected-faces-sw"; 2306 private static final String KEY_RECORDING_HINT = "recording-hint"; 2307 private static final String KEY_VIDEO_SNAPSHOT_SUPPORTED = "video-snapshot-supported"; 2308 private static final String KEY_VIDEO_STABILIZATION = "video-stabilization"; 2309 private static final String KEY_VIDEO_STABILIZATION_SUPPORTED = "video-stabilization-supported"; 2310 2311 // Parameter key suffix for supported values. 2312 private static final String SUPPORTED_VALUES_SUFFIX = "-values"; 2313 2314 private static final String TRUE = "true"; 2315 private static final String FALSE = "false"; 2316 2317 // Values for white balance settings. 2318 public static final String WHITE_BALANCE_AUTO = "auto"; 2319 public static final String WHITE_BALANCE_INCANDESCENT = "incandescent"; 2320 public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent"; 2321 public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent"; 2322 public static final String WHITE_BALANCE_DAYLIGHT = "daylight"; 2323 public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight"; 2324 public static final String WHITE_BALANCE_TWILIGHT = "twilight"; 2325 public static final String WHITE_BALANCE_SHADE = "shade"; 2326 2327 // Values for color effect settings. 2328 public static final String EFFECT_NONE = "none"; 2329 public static final String EFFECT_MONO = "mono"; 2330 public static final String EFFECT_NEGATIVE = "negative"; 2331 public static final String EFFECT_SOLARIZE = "solarize"; 2332 public static final String EFFECT_SEPIA = "sepia"; 2333 public static final String EFFECT_POSTERIZE = "posterize"; 2334 public static final String EFFECT_WHITEBOARD = "whiteboard"; 2335 public static final String EFFECT_BLACKBOARD = "blackboard"; 2336 public static final String EFFECT_AQUA = "aqua"; 2337 2338 // Values for antibanding settings. 2339 public static final String ANTIBANDING_AUTO = "auto"; 2340 public static final String ANTIBANDING_50HZ = "50hz"; 2341 public static final String ANTIBANDING_60HZ = "60hz"; 2342 public static final String ANTIBANDING_OFF = "off"; 2343 2344 // Values for flash mode settings. 2345 /** 2346 * Flash will not be fired. 2347 */ 2348 public static final String FLASH_MODE_OFF = "off"; 2349 2350 /** 2351 * Flash will be fired automatically when required. The flash may be fired 2352 * during preview, auto-focus, or snapshot depending on the driver. 2353 */ 2354 public static final String FLASH_MODE_AUTO = "auto"; 2355 2356 /** 2357 * Flash will always be fired during snapshot. The flash may also be 2358 * fired during preview or auto-focus depending on the driver. 2359 */ 2360 public static final String FLASH_MODE_ON = "on"; 2361 2362 /** 2363 * Flash will be fired in red-eye reduction mode. 2364 */ 2365 public static final String FLASH_MODE_RED_EYE = "red-eye"; 2366 2367 /** 2368 * Constant emission of light during preview, auto-focus and snapshot. 2369 * This can also be used for video recording. 2370 */ 2371 public static final String FLASH_MODE_TORCH = "torch"; 2372 2373 /** 2374 * Scene mode is off. 2375 */ 2376 public static final String SCENE_MODE_AUTO = "auto"; 2377 2378 /** 2379 * Take photos of fast moving objects. Same as {@link 2380 * #SCENE_MODE_SPORTS}. 2381 */ 2382 public static final String SCENE_MODE_ACTION = "action"; 2383 2384 /** 2385 * Take people pictures. 2386 */ 2387 public static final String SCENE_MODE_PORTRAIT = "portrait"; 2388 2389 /** 2390 * Take pictures on distant objects. 2391 */ 2392 public static final String SCENE_MODE_LANDSCAPE = "landscape"; 2393 2394 /** 2395 * Take photos at night. 2396 */ 2397 public static final String SCENE_MODE_NIGHT = "night"; 2398 2399 /** 2400 * Take people pictures at night. 2401 */ 2402 public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait"; 2403 2404 /** 2405 * Take photos in a theater. Flash light is off. 2406 */ 2407 public static final String SCENE_MODE_THEATRE = "theatre"; 2408 2409 /** 2410 * Take pictures on the beach. 2411 */ 2412 public static final String SCENE_MODE_BEACH = "beach"; 2413 2414 /** 2415 * Take pictures on the snow. 2416 */ 2417 public static final String SCENE_MODE_SNOW = "snow"; 2418 2419 /** 2420 * Take sunset photos. 2421 */ 2422 public static final String SCENE_MODE_SUNSET = "sunset"; 2423 2424 /** 2425 * Avoid blurry pictures (for example, due to hand shake). 2426 */ 2427 public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto"; 2428 2429 /** 2430 * For shooting firework displays. 2431 */ 2432 public static final String SCENE_MODE_FIREWORKS = "fireworks"; 2433 2434 /** 2435 * Take photos of fast moving objects. Same as {@link 2436 * #SCENE_MODE_ACTION}. 2437 */ 2438 public static final String SCENE_MODE_SPORTS = "sports"; 2439 2440 /** 2441 * Take indoor low-light shot. 2442 */ 2443 public static final String SCENE_MODE_PARTY = "party"; 2444 2445 /** 2446 * Capture the naturally warm color of scenes lit by candles. 2447 */ 2448 public static final String SCENE_MODE_CANDLELIGHT = "candlelight"; 2449 2450 /** 2451 * Applications are looking for a barcode. Camera driver will be 2452 * optimized for barcode reading. 2453 */ 2454 public static final String SCENE_MODE_BARCODE = "barcode"; 2455 2456 /** 2457 * Capture a scene using high dynamic range imaging techniques. The 2458 * camera will return an image that has an extended dynamic range 2459 * compared to a regular capture. Capturing such an image may take 2460 * longer than a regular capture. 2461 */ 2462 public static final String SCENE_MODE_HDR = "hdr"; 2463 2464 /** 2465 * Auto-focus mode. Applications should call {@link 2466 * #autoFocus(AutoFocusCallback)} to start the focus in this mode. 2467 */ 2468 public static final String FOCUS_MODE_AUTO = "auto"; 2469 2470 /** 2471 * Focus is set at infinity. Applications should not call 2472 * {@link #autoFocus(AutoFocusCallback)} in this mode. 2473 */ 2474 public static final String FOCUS_MODE_INFINITY = "infinity"; 2475 2476 /** 2477 * Macro (close-up) focus mode. Applications should call 2478 * {@link #autoFocus(AutoFocusCallback)} to start the focus in this 2479 * mode. 2480 */ 2481 public static final String FOCUS_MODE_MACRO = "macro"; 2482 2483 /** 2484 * Focus is fixed. The camera is always in this mode if the focus is not 2485 * adjustable. If the camera has auto-focus, this mode can fix the 2486 * focus, which is usually at hyperfocal distance. Applications should 2487 * not call {@link #autoFocus(AutoFocusCallback)} in this mode. 2488 */ 2489 public static final String FOCUS_MODE_FIXED = "fixed"; 2490 2491 /** 2492 * Extended depth of field (EDOF). Focusing is done digitally and 2493 * continuously. Applications should not call {@link 2494 * #autoFocus(AutoFocusCallback)} in this mode. 2495 */ 2496 public static final String FOCUS_MODE_EDOF = "edof"; 2497 2498 /** 2499 * Continuous auto focus mode intended for video recording. The camera 2500 * continuously tries to focus. This is the best choice for video 2501 * recording because the focus changes smoothly . Applications still can 2502 * call {@link #takePicture(Camera.ShutterCallback, 2503 * Camera.PictureCallback, Camera.PictureCallback)} in this mode but the 2504 * subject may not be in focus. Auto focus starts when the parameter is 2505 * set. 2506 * 2507 * <p>Since API level 14, applications can call {@link 2508 * #autoFocus(AutoFocusCallback)} in this mode. The focus callback will 2509 * immediately return with a boolean that indicates whether the focus is 2510 * sharp or not. The focus position is locked after autoFocus call. If 2511 * applications want to resume the continuous focus, cancelAutoFocus 2512 * must be called. Restarting the preview will not resume the continuous 2513 * autofocus. To stop continuous focus, applications should change the 2514 * focus mode to other modes. 2515 * 2516 * @see #FOCUS_MODE_CONTINUOUS_PICTURE 2517 */ 2518 public static final String FOCUS_MODE_CONTINUOUS_VIDEO = "continuous-video"; 2519 2520 /** 2521 * Continuous auto focus mode intended for taking pictures. The camera 2522 * continuously tries to focus. The speed of focus change is more 2523 * aggressive than {@link #FOCUS_MODE_CONTINUOUS_VIDEO}. Auto focus 2524 * starts when the parameter is set. 2525 * 2526 * <p>Applications can call {@link #autoFocus(AutoFocusCallback)} in 2527 * this mode. If the autofocus is in the middle of scanning, the focus 2528 * callback will return when it completes. If the autofocus is not 2529 * scanning, the focus callback will immediately return with a boolean 2530 * that indicates whether the focus is sharp or not. The apps can then 2531 * decide if they want to take a picture immediately or to change the 2532 * focus mode to auto, and run a full autofocus cycle. The focus 2533 * position is locked after autoFocus call. If applications want to 2534 * resume the continuous focus, cancelAutoFocus must be called. 2535 * Restarting the preview will not resume the continuous autofocus. To 2536 * stop continuous focus, applications should change the focus mode to 2537 * other modes. 2538 * 2539 * @see #FOCUS_MODE_CONTINUOUS_VIDEO 2540 */ 2541 public static final String FOCUS_MODE_CONTINUOUS_PICTURE = "continuous-picture"; 2542 2543 // Indices for focus distance array. 2544 /** 2545 * The array index of near focus distance for use with 2546 * {@link #getFocusDistances(float[])}. 2547 */ 2548 public static final int FOCUS_DISTANCE_NEAR_INDEX = 0; 2549 2550 /** 2551 * The array index of optimal focus distance for use with 2552 * {@link #getFocusDistances(float[])}. 2553 */ 2554 public static final int FOCUS_DISTANCE_OPTIMAL_INDEX = 1; 2555 2556 /** 2557 * The array index of far focus distance for use with 2558 * {@link #getFocusDistances(float[])}. 2559 */ 2560 public static final int FOCUS_DISTANCE_FAR_INDEX = 2; 2561 2562 /** 2563 * The array index of minimum preview fps for use with {@link 2564 * #getPreviewFpsRange(int[])} or {@link 2565 * #getSupportedPreviewFpsRange()}. 2566 */ 2567 public static final int PREVIEW_FPS_MIN_INDEX = 0; 2568 2569 /** 2570 * The array index of maximum preview fps for use with {@link 2571 * #getPreviewFpsRange(int[])} or {@link 2572 * #getSupportedPreviewFpsRange()}. 2573 */ 2574 public static final int PREVIEW_FPS_MAX_INDEX = 1; 2575 2576 // Formats for setPreviewFormat and setPictureFormat. 2577 private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp"; 2578 private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp"; 2579 private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv"; 2580 private static final String PIXEL_FORMAT_YUV420P = "yuv420p"; 2581 private static final String PIXEL_FORMAT_RGB565 = "rgb565"; 2582 private static final String PIXEL_FORMAT_JPEG = "jpeg"; 2583 private static final String PIXEL_FORMAT_BAYER_RGGB = "bayer-rggb"; 2584 2585 /** 2586 * Order matters: Keys that are {@link #set(String, String) set} later 2587 * will take precedence over keys that are set earlier (if the two keys 2588 * conflict with each other). 2589 * 2590 * <p>One example is {@link #setPreviewFpsRange(int, int)} , since it 2591 * conflicts with {@link #setPreviewFrameRate(int)} whichever key is set later 2592 * is the one that will take precedence. 2593 * </p> 2594 */ 2595 private final LinkedHashMap<String, String> mMap; 2596 2597 private Parameters() { 2598 mMap = new LinkedHashMap<String, String>(/*initialCapacity*/64); 2599 } 2600 2601 /** 2602 * Overwrite existing parameters with a copy of the ones from {@code other}. 2603 * 2604 * <b>For use by the legacy shim only.</b> 2605 * 2606 * @hide 2607 */ 2608 public void copyFrom(Parameters other) { 2609 if (other == null) { 2610 throw new NullPointerException("other must not be null"); 2611 } 2612 2613 mMap.putAll(other.mMap); 2614 } 2615 2616 private Camera getOuter() { 2617 return Camera.this; 2618 } 2619 2620 2621 /** 2622 * Value equality check. 2623 * 2624 * @hide 2625 */ 2626 public boolean same(Parameters other) { 2627 if (this == other) { 2628 return true; 2629 } 2630 return other != null && Parameters.this.mMap.equals(other.mMap); 2631 } 2632 2633 /** 2634 * Writes the current Parameters to the log. 2635 * @hide 2636 * @deprecated 2637 */ 2638 @Deprecated 2639 public void dump() { 2640 Log.e(TAG, "dump: size=" + mMap.size()); 2641 for (String k : mMap.keySet()) { 2642 Log.e(TAG, "dump: " + k + "=" + mMap.get(k)); 2643 } 2644 } 2645 2646 /** 2647 * Creates a single string with all the parameters set in 2648 * this Parameters object. 2649 * <p>The {@link #unflatten(String)} method does the reverse.</p> 2650 * 2651 * @return a String with all values from this Parameters object, in 2652 * semi-colon delimited key-value pairs 2653 */ 2654 public String flatten() { 2655 StringBuilder flattened = new StringBuilder(128); 2656 for (String k : mMap.keySet()) { 2657 flattened.append(k); 2658 flattened.append("="); 2659 flattened.append(mMap.get(k)); 2660 flattened.append(";"); 2661 } 2662 // chop off the extra semicolon at the end 2663 flattened.deleteCharAt(flattened.length()-1); 2664 return flattened.toString(); 2665 } 2666 2667 /** 2668 * Takes a flattened string of parameters and adds each one to 2669 * this Parameters object. 2670 * <p>The {@link #flatten()} method does the reverse.</p> 2671 * 2672 * @param flattened a String of parameters (key-value paired) that 2673 * are semi-colon delimited 2674 */ 2675 public void unflatten(String flattened) { 2676 mMap.clear(); 2677 2678 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(';'); 2679 splitter.setString(flattened); 2680 for (String kv : splitter) { 2681 int pos = kv.indexOf('='); 2682 if (pos == -1) { 2683 continue; 2684 } 2685 String k = kv.substring(0, pos); 2686 String v = kv.substring(pos + 1); 2687 mMap.put(k, v); 2688 } 2689 } 2690 2691 public void remove(String key) { 2692 mMap.remove(key); 2693 } 2694 2695 /** 2696 * Sets a String parameter. 2697 * 2698 * @param key the key name for the parameter 2699 * @param value the String value of the parameter 2700 */ 2701 public void set(String key, String value) { 2702 if (key.indexOf('=') != -1 || key.indexOf(';') != -1 || key.indexOf(0) != -1) { 2703 Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ; or \\0)"); 2704 return; 2705 } 2706 if (value.indexOf('=') != -1 || value.indexOf(';') != -1 || value.indexOf(0) != -1) { 2707 Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ; or \\0)"); 2708 return; 2709 } 2710 2711 put(key, value); 2712 } 2713 2714 /** 2715 * Sets an integer parameter. 2716 * 2717 * @param key the key name for the parameter 2718 * @param value the int value of the parameter 2719 */ 2720 public void set(String key, int value) { 2721 put(key, Integer.toString(value)); 2722 } 2723 2724 private void put(String key, String value) { 2725 /* 2726 * Remove the key if it already exists. 2727 * 2728 * This way setting a new value for an already existing key will always move 2729 * that key to be ordered the latest in the map. 2730 */ 2731 mMap.remove(key); 2732 mMap.put(key, value); 2733 } 2734 2735 private void set(String key, List<Area> areas) { 2736 if (areas == null) { 2737 set(key, "(0,0,0,0,0)"); 2738 } else { 2739 StringBuilder buffer = new StringBuilder(); 2740 for (int i = 0; i < areas.size(); i++) { 2741 Area area = areas.get(i); 2742 Rect rect = area.rect; 2743 buffer.append('('); 2744 buffer.append(rect.left); 2745 buffer.append(','); 2746 buffer.append(rect.top); 2747 buffer.append(','); 2748 buffer.append(rect.right); 2749 buffer.append(','); 2750 buffer.append(rect.bottom); 2751 buffer.append(','); 2752 buffer.append(area.weight); 2753 buffer.append(')'); 2754 if (i != areas.size() - 1) buffer.append(','); 2755 } 2756 set(key, buffer.toString()); 2757 } 2758 } 2759 2760 /** 2761 * Returns the value of a String parameter. 2762 * 2763 * @param key the key name for the parameter 2764 * @return the String value of the parameter 2765 */ 2766 public String get(String key) { 2767 return mMap.get(key); 2768 } 2769 2770 /** 2771 * Returns the value of an integer parameter. 2772 * 2773 * @param key the key name for the parameter 2774 * @return the int value of the parameter 2775 */ 2776 public int getInt(String key) { 2777 return Integer.parseInt(mMap.get(key)); 2778 } 2779 2780 /** 2781 * Sets the dimensions for preview pictures. If the preview has already 2782 * started, applications should stop the preview first before changing 2783 * preview size. 2784 * 2785 * The sides of width and height are based on camera orientation. That 2786 * is, the preview size is the size before it is rotated by display 2787 * orientation. So applications need to consider the display orientation 2788 * while setting preview size. For example, suppose the camera supports 2789 * both 480x320 and 320x480 preview sizes. The application wants a 3:2 2790 * preview ratio. If the display orientation is set to 0 or 180, preview 2791 * size should be set to 480x320. If the display orientation is set to 2792 * 90 or 270, preview size should be set to 320x480. The display 2793 * orientation should also be considered while setting picture size and 2794 * thumbnail size. 2795 * 2796 * @param width the width of the pictures, in pixels 2797 * @param height the height of the pictures, in pixels 2798 * @see #setDisplayOrientation(int) 2799 * @see #getCameraInfo(int, CameraInfo) 2800 * @see #setPictureSize(int, int) 2801 * @see #setJpegThumbnailSize(int, int) 2802 */ 2803 public void setPreviewSize(int width, int height) { 2804 String v = Integer.toString(width) + "x" + Integer.toString(height); 2805 set(KEY_PREVIEW_SIZE, v); 2806 } 2807 2808 /** 2809 * Returns the dimensions setting for preview pictures. 2810 * 2811 * @return a Size object with the width and height setting 2812 * for the preview picture 2813 */ 2814 public Size getPreviewSize() { 2815 String pair = get(KEY_PREVIEW_SIZE); 2816 return strToSize(pair); 2817 } 2818 2819 /** 2820 * Gets the supported preview sizes. 2821 * 2822 * @return a list of Size object. This method will always return a list 2823 * with at least one element. 2824 */ 2825 public List<Size> getSupportedPreviewSizes() { 2826 String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX); 2827 return splitSize(str); 2828 } 2829 2830 /** 2831 * <p>Gets the supported video frame sizes that can be used by 2832 * MediaRecorder.</p> 2833 * 2834 * <p>If the returned list is not null, the returned list will contain at 2835 * least one Size and one of the sizes in the returned list must be 2836 * passed to MediaRecorder.setVideoSize() for camcorder application if 2837 * camera is used as the video source. In this case, the size of the 2838 * preview can be different from the resolution of the recorded video 2839 * during video recording.</p> 2840 * 2841 * @return a list of Size object if camera has separate preview and 2842 * video output; otherwise, null is returned. 2843 * @see #getPreferredPreviewSizeForVideo() 2844 */ 2845 public List<Size> getSupportedVideoSizes() { 2846 String str = get(KEY_VIDEO_SIZE + SUPPORTED_VALUES_SUFFIX); 2847 return splitSize(str); 2848 } 2849 2850 /** 2851 * Returns the preferred or recommended preview size (width and height) 2852 * in pixels for video recording. Camcorder applications should 2853 * set the preview size to a value that is not larger than the 2854 * preferred preview size. In other words, the product of the width 2855 * and height of the preview size should not be larger than that of 2856 * the preferred preview size. In addition, we recommend to choose a 2857 * preview size that has the same aspect ratio as the resolution of 2858 * video to be recorded. 2859 * 2860 * @return the preferred preview size (width and height) in pixels for 2861 * video recording if getSupportedVideoSizes() does not return 2862 * null; otherwise, null is returned. 2863 * @see #getSupportedVideoSizes() 2864 */ 2865 public Size getPreferredPreviewSizeForVideo() { 2866 String pair = get(KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO); 2867 return strToSize(pair); 2868 } 2869 2870 /** 2871 * <p>Sets the dimensions for EXIF thumbnail in Jpeg picture. If 2872 * applications set both width and height to 0, EXIF will not contain 2873 * thumbnail.</p> 2874 * 2875 * <p>Applications need to consider the display orientation. See {@link 2876 * #setPreviewSize(int,int)} for reference.</p> 2877 * 2878 * @param width the width of the thumbnail, in pixels 2879 * @param height the height of the thumbnail, in pixels 2880 * @see #setPreviewSize(int,int) 2881 */ 2882 public void setJpegThumbnailSize(int width, int height) { 2883 set(KEY_JPEG_THUMBNAIL_WIDTH, width); 2884 set(KEY_JPEG_THUMBNAIL_HEIGHT, height); 2885 } 2886 2887 /** 2888 * Returns the dimensions for EXIF thumbnail in Jpeg picture. 2889 * 2890 * @return a Size object with the height and width setting for the EXIF 2891 * thumbnails 2892 */ 2893 public Size getJpegThumbnailSize() { 2894 return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH), 2895 getInt(KEY_JPEG_THUMBNAIL_HEIGHT)); 2896 } 2897 2898 /** 2899 * Gets the supported jpeg thumbnail sizes. 2900 * 2901 * @return a list of Size object. This method will always return a list 2902 * with at least two elements. Size 0,0 (no thumbnail) is always 2903 * supported. 2904 */ 2905 public List<Size> getSupportedJpegThumbnailSizes() { 2906 String str = get(KEY_JPEG_THUMBNAIL_SIZE + SUPPORTED_VALUES_SUFFIX); 2907 return splitSize(str); 2908 } 2909 2910 /** 2911 * Sets the quality of the EXIF thumbnail in Jpeg picture. 2912 * 2913 * @param quality the JPEG quality of the EXIF thumbnail. The range is 1 2914 * to 100, with 100 being the best. 2915 */ 2916 public void setJpegThumbnailQuality(int quality) { 2917 set(KEY_JPEG_THUMBNAIL_QUALITY, quality); 2918 } 2919 2920 /** 2921 * Returns the quality setting for the EXIF thumbnail in Jpeg picture. 2922 * 2923 * @return the JPEG quality setting of the EXIF thumbnail. 2924 */ 2925 public int getJpegThumbnailQuality() { 2926 return getInt(KEY_JPEG_THUMBNAIL_QUALITY); 2927 } 2928 2929 /** 2930 * Sets Jpeg quality of captured picture. 2931 * 2932 * @param quality the JPEG quality of captured picture. The range is 1 2933 * to 100, with 100 being the best. 2934 */ 2935 public void setJpegQuality(int quality) { 2936 set(KEY_JPEG_QUALITY, quality); 2937 } 2938 2939 /** 2940 * Returns the quality setting for the JPEG picture. 2941 * 2942 * @return the JPEG picture quality setting. 2943 */ 2944 public int getJpegQuality() { 2945 return getInt(KEY_JPEG_QUALITY); 2946 } 2947 2948 /** 2949 * Sets the rate at which preview frames are received. This is the 2950 * target frame rate. The actual frame rate depends on the driver. 2951 * 2952 * @param fps the frame rate (frames per second) 2953 * @deprecated replaced by {@link #setPreviewFpsRange(int,int)} 2954 */ 2955 @Deprecated 2956 public void setPreviewFrameRate(int fps) { 2957 set(KEY_PREVIEW_FRAME_RATE, fps); 2958 } 2959 2960 /** 2961 * Returns the setting for the rate at which preview frames are 2962 * received. This is the target frame rate. The actual frame rate 2963 * depends on the driver. 2964 * 2965 * @return the frame rate setting (frames per second) 2966 * @deprecated replaced by {@link #getPreviewFpsRange(int[])} 2967 */ 2968 @Deprecated 2969 public int getPreviewFrameRate() { 2970 return getInt(KEY_PREVIEW_FRAME_RATE); 2971 } 2972 2973 /** 2974 * Gets the supported preview frame rates. 2975 * 2976 * @return a list of supported preview frame rates. null if preview 2977 * frame rate setting is not supported. 2978 * @deprecated replaced by {@link #getSupportedPreviewFpsRange()} 2979 */ 2980 @Deprecated 2981 public List<Integer> getSupportedPreviewFrameRates() { 2982 String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX); 2983 return splitInt(str); 2984 } 2985 2986 /** 2987 * Sets the minimum and maximum preview fps. This controls the rate of 2988 * preview frames received in {@link PreviewCallback}. The minimum and 2989 * maximum preview fps must be one of the elements from {@link 2990 * #getSupportedPreviewFpsRange}. 2991 * 2992 * @param min the minimum preview fps (scaled by 1000). 2993 * @param max the maximum preview fps (scaled by 1000). 2994 * @throws RuntimeException if fps range is invalid. 2995 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 2996 * @see #getSupportedPreviewFpsRange() 2997 */ 2998 public void setPreviewFpsRange(int min, int max) { 2999 set(KEY_PREVIEW_FPS_RANGE, "" + min + "," + max); 3000 } 3001 3002 /** 3003 * Returns the current minimum and maximum preview fps. The values are 3004 * one of the elements returned by {@link #getSupportedPreviewFpsRange}. 3005 * 3006 * @return range the minimum and maximum preview fps (scaled by 1000). 3007 * @see #PREVIEW_FPS_MIN_INDEX 3008 * @see #PREVIEW_FPS_MAX_INDEX 3009 * @see #getSupportedPreviewFpsRange() 3010 */ 3011 public void getPreviewFpsRange(int[] range) { 3012 if (range == null || range.length != 2) { 3013 throw new IllegalArgumentException( 3014 "range must be an array with two elements."); 3015 } 3016 splitInt(get(KEY_PREVIEW_FPS_RANGE), range); 3017 } 3018 3019 /** 3020 * Gets the supported preview fps (frame-per-second) ranges. Each range 3021 * contains a minimum fps and maximum fps. If minimum fps equals to 3022 * maximum fps, the camera outputs frames in fixed frame rate. If not, 3023 * the camera outputs frames in auto frame rate. The actual frame rate 3024 * fluctuates between the minimum and the maximum. The values are 3025 * multiplied by 1000 and represented in integers. For example, if frame 3026 * rate is 26.623 frames per second, the value is 26623. 3027 * 3028 * @return a list of supported preview fps ranges. This method returns a 3029 * list with at least one element. Every element is an int array 3030 * of two values - minimum fps and maximum fps. The list is 3031 * sorted from small to large (first by maximum fps and then 3032 * minimum fps). 3033 * @see #PREVIEW_FPS_MIN_INDEX 3034 * @see #PREVIEW_FPS_MAX_INDEX 3035 */ 3036 public List<int[]> getSupportedPreviewFpsRange() { 3037 String str = get(KEY_PREVIEW_FPS_RANGE + SUPPORTED_VALUES_SUFFIX); 3038 return splitRange(str); 3039 } 3040 3041 /** 3042 * Sets the image format for preview pictures. 3043 * <p>If this is never called, the default format will be 3044 * {@link android.graphics.ImageFormat#NV21}, which 3045 * uses the NV21 encoding format.</p> 3046 * 3047 * <p>Use {@link Parameters#getSupportedPreviewFormats} to get a list of 3048 * the available preview formats. 3049 * 3050 * <p>It is strongly recommended that either 3051 * {@link android.graphics.ImageFormat#NV21} or 3052 * {@link android.graphics.ImageFormat#YV12} is used, since 3053 * they are supported by all camera devices.</p> 3054 * 3055 * <p>For YV12, the image buffer that is received is not necessarily 3056 * tightly packed, as there may be padding at the end of each row of 3057 * pixel data, as described in 3058 * {@link android.graphics.ImageFormat#YV12}. For camera callback data, 3059 * it can be assumed that the stride of the Y and UV data is the 3060 * smallest possible that meets the alignment requirements. That is, if 3061 * the preview size is <var>width x height</var>, then the following 3062 * equations describe the buffer index for the beginning of row 3063 * <var>y</var> for the Y plane and row <var>c</var> for the U and V 3064 * planes: 3065 * 3066 * <pre>{@code 3067 * yStride = (int) ceil(width / 16.0) * 16; 3068 * uvStride = (int) ceil( (yStride / 2) / 16.0) * 16; 3069 * ySize = yStride * height; 3070 * uvSize = uvStride * height / 2; 3071 * yRowIndex = yStride * y; 3072 * uRowIndex = ySize + uvSize + uvStride * c; 3073 * vRowIndex = ySize + uvStride * c; 3074 * size = ySize + uvSize * 2; 3075 * } 3076 *</pre> 3077 * 3078 * @param pixel_format the desired preview picture format, defined by 3079 * one of the {@link android.graphics.ImageFormat} constants. (E.g., 3080 * <var>ImageFormat.NV21</var> (default), or 3081 * <var>ImageFormat.YV12</var>) 3082 * 3083 * @see android.graphics.ImageFormat 3084 * @see android.hardware.Camera.Parameters#getSupportedPreviewFormats 3085 */ 3086 public void setPreviewFormat(int pixel_format) { 3087 String s = cameraFormatForPixelFormat(pixel_format); 3088 if (s == null) { 3089 throw new IllegalArgumentException( 3090 "Invalid pixel_format=" + pixel_format); 3091 } 3092 3093 set(KEY_PREVIEW_FORMAT, s); 3094 } 3095 3096 /** 3097 * Returns the image format for preview frames got from 3098 * {@link PreviewCallback}. 3099 * 3100 * @return the preview format. 3101 * @see android.graphics.ImageFormat 3102 * @see #setPreviewFormat 3103 */ 3104 public int getPreviewFormat() { 3105 return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT)); 3106 } 3107 3108 /** 3109 * Gets the supported preview formats. {@link android.graphics.ImageFormat#NV21} 3110 * is always supported. {@link android.graphics.ImageFormat#YV12} 3111 * is always supported since API level 12. 3112 * 3113 * @return a list of supported preview formats. This method will always 3114 * return a list with at least one element. 3115 * @see android.graphics.ImageFormat 3116 * @see #setPreviewFormat 3117 */ 3118 public List<Integer> getSupportedPreviewFormats() { 3119 String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX); 3120 ArrayList<Integer> formats = new ArrayList<Integer>(); 3121 for (String s : split(str)) { 3122 int f = pixelFormatForCameraFormat(s); 3123 if (f == ImageFormat.UNKNOWN) continue; 3124 formats.add(f); 3125 } 3126 return formats; 3127 } 3128 3129 /** 3130 * <p>Sets the dimensions for pictures.</p> 3131 * 3132 * <p>Applications need to consider the display orientation. See {@link 3133 * #setPreviewSize(int,int)} for reference.</p> 3134 * 3135 * @param width the width for pictures, in pixels 3136 * @param height the height for pictures, in pixels 3137 * @see #setPreviewSize(int,int) 3138 * 3139 */ 3140 public void setPictureSize(int width, int height) { 3141 String v = Integer.toString(width) + "x" + Integer.toString(height); 3142 set(KEY_PICTURE_SIZE, v); 3143 } 3144 3145 /** 3146 * Returns the dimension setting for pictures. 3147 * 3148 * @return a Size object with the height and width setting 3149 * for pictures 3150 */ 3151 public Size getPictureSize() { 3152 String pair = get(KEY_PICTURE_SIZE); 3153 return strToSize(pair); 3154 } 3155 3156 /** 3157 * Gets the supported picture sizes. 3158 * 3159 * @return a list of supported picture sizes. This method will always 3160 * return a list with at least one element. 3161 */ 3162 public List<Size> getSupportedPictureSizes() { 3163 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 3164 return splitSize(str); 3165 } 3166 3167 /** 3168 * Sets the image format for pictures. 3169 * 3170 * @param pixel_format the desired picture format 3171 * (<var>ImageFormat.NV21</var>, 3172 * <var>ImageFormat.RGB_565</var>, or 3173 * <var>ImageFormat.JPEG</var>) 3174 * @see android.graphics.ImageFormat 3175 */ 3176 public void setPictureFormat(int pixel_format) { 3177 String s = cameraFormatForPixelFormat(pixel_format); 3178 if (s == null) { 3179 throw new IllegalArgumentException( 3180 "Invalid pixel_format=" + pixel_format); 3181 } 3182 3183 set(KEY_PICTURE_FORMAT, s); 3184 } 3185 3186 /** 3187 * Returns the image format for pictures. 3188 * 3189 * @return the picture format 3190 * @see android.graphics.ImageFormat 3191 */ 3192 public int getPictureFormat() { 3193 return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT)); 3194 } 3195 3196 /** 3197 * Gets the supported picture formats. 3198 * 3199 * @return supported picture formats. This method will always return a 3200 * list with at least one element. 3201 * @see android.graphics.ImageFormat 3202 */ 3203 public List<Integer> getSupportedPictureFormats() { 3204 String str = get(KEY_PICTURE_FORMAT + SUPPORTED_VALUES_SUFFIX); 3205 ArrayList<Integer> formats = new ArrayList<Integer>(); 3206 for (String s : split(str)) { 3207 int f = pixelFormatForCameraFormat(s); 3208 if (f == ImageFormat.UNKNOWN) continue; 3209 formats.add(f); 3210 } 3211 return formats; 3212 } 3213 3214 private String cameraFormatForPixelFormat(int pixel_format) { 3215 switch(pixel_format) { 3216 case ImageFormat.NV16: return PIXEL_FORMAT_YUV422SP; 3217 case ImageFormat.NV21: return PIXEL_FORMAT_YUV420SP; 3218 case ImageFormat.YUY2: return PIXEL_FORMAT_YUV422I; 3219 case ImageFormat.YV12: return PIXEL_FORMAT_YUV420P; 3220 case ImageFormat.RGB_565: return PIXEL_FORMAT_RGB565; 3221 case ImageFormat.JPEG: return PIXEL_FORMAT_JPEG; 3222 default: return null; 3223 } 3224 } 3225 3226 private int pixelFormatForCameraFormat(String format) { 3227 if (format == null) 3228 return ImageFormat.UNKNOWN; 3229 3230 if (format.equals(PIXEL_FORMAT_YUV422SP)) 3231 return ImageFormat.NV16; 3232 3233 if (format.equals(PIXEL_FORMAT_YUV420SP)) 3234 return ImageFormat.NV21; 3235 3236 if (format.equals(PIXEL_FORMAT_YUV422I)) 3237 return ImageFormat.YUY2; 3238 3239 if (format.equals(PIXEL_FORMAT_YUV420P)) 3240 return ImageFormat.YV12; 3241 3242 if (format.equals(PIXEL_FORMAT_RGB565)) 3243 return ImageFormat.RGB_565; 3244 3245 if (format.equals(PIXEL_FORMAT_JPEG)) 3246 return ImageFormat.JPEG; 3247 3248 return ImageFormat.UNKNOWN; 3249 } 3250 3251 /** 3252 * Sets the clockwise rotation angle in degrees relative to the 3253 * orientation of the camera. This affects the pictures returned from 3254 * JPEG {@link PictureCallback}. The camera driver may set orientation 3255 * in the EXIF header without rotating the picture. Or the driver may 3256 * rotate the picture and the EXIF thumbnail. If the Jpeg picture is 3257 * rotated, the orientation in the EXIF header will be missing or 1 (row 3258 * #0 is top and column #0 is left side). 3259 * 3260 * <p> 3261 * If applications want to rotate the picture to match the orientation 3262 * of what users see, apps should use 3263 * {@link android.view.OrientationEventListener} and 3264 * {@link android.hardware.Camera.CameraInfo}. The value from 3265 * OrientationEventListener is relative to the natural orientation of 3266 * the device. CameraInfo.orientation is the angle between camera 3267 * orientation and natural device orientation. The sum of the two is the 3268 * rotation angle for back-facing camera. The difference of the two is 3269 * the rotation angle for front-facing camera. Note that the JPEG 3270 * pictures of front-facing cameras are not mirrored as in preview 3271 * display. 3272 * 3273 * <p> 3274 * For example, suppose the natural orientation of the device is 3275 * portrait. The device is rotated 270 degrees clockwise, so the device 3276 * orientation is 270. Suppose a back-facing camera sensor is mounted in 3277 * landscape and the top side of the camera sensor is aligned with the 3278 * right edge of the display in natural orientation. So the camera 3279 * orientation is 90. The rotation should be set to 0 (270 + 90). 3280 * 3281 * <p>The reference code is as follows. 3282 * 3283 * <pre> 3284 * public void onOrientationChanged(int orientation) { 3285 * if (orientation == ORIENTATION_UNKNOWN) return; 3286 * android.hardware.Camera.CameraInfo info = 3287 * new android.hardware.Camera.CameraInfo(); 3288 * android.hardware.Camera.getCameraInfo(cameraId, info); 3289 * orientation = (orientation + 45) / 90 * 90; 3290 * int rotation = 0; 3291 * if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 3292 * rotation = (info.orientation - orientation + 360) % 360; 3293 * } else { // back-facing camera 3294 * rotation = (info.orientation + orientation) % 360; 3295 * } 3296 * mParameters.setRotation(rotation); 3297 * } 3298 * </pre> 3299 * 3300 * @param rotation The rotation angle in degrees relative to the 3301 * orientation of the camera. Rotation can only be 0, 3302 * 90, 180 or 270. 3303 * @throws IllegalArgumentException if rotation value is invalid. 3304 * @see android.view.OrientationEventListener 3305 * @see #getCameraInfo(int, CameraInfo) 3306 */ 3307 public void setRotation(int rotation) { 3308 if (rotation == 0 || rotation == 90 || rotation == 180 3309 || rotation == 270) { 3310 set(KEY_ROTATION, Integer.toString(rotation)); 3311 } else { 3312 throw new IllegalArgumentException( 3313 "Invalid rotation=" + rotation); 3314 } 3315 } 3316 3317 /** 3318 * Sets GPS latitude coordinate. This will be stored in JPEG EXIF 3319 * header. 3320 * 3321 * @param latitude GPS latitude coordinate. 3322 */ 3323 public void setGpsLatitude(double latitude) { 3324 set(KEY_GPS_LATITUDE, Double.toString(latitude)); 3325 } 3326 3327 /** 3328 * Sets GPS longitude coordinate. This will be stored in JPEG EXIF 3329 * header. 3330 * 3331 * @param longitude GPS longitude coordinate. 3332 */ 3333 public void setGpsLongitude(double longitude) { 3334 set(KEY_GPS_LONGITUDE, Double.toString(longitude)); 3335 } 3336 3337 /** 3338 * Sets GPS altitude. This will be stored in JPEG EXIF header. 3339 * 3340 * @param altitude GPS altitude in meters. 3341 */ 3342 public void setGpsAltitude(double altitude) { 3343 set(KEY_GPS_ALTITUDE, Double.toString(altitude)); 3344 } 3345 3346 /** 3347 * Sets GPS timestamp. This will be stored in JPEG EXIF header. 3348 * 3349 * @param timestamp GPS timestamp (UTC in seconds since January 1, 3350 * 1970). 3351 */ 3352 public void setGpsTimestamp(long timestamp) { 3353 set(KEY_GPS_TIMESTAMP, Long.toString(timestamp)); 3354 } 3355 3356 /** 3357 * Sets GPS processing method. The method will be stored in a UTF-8 string up to 31 bytes 3358 * long, in the JPEG EXIF header. 3359 * 3360 * @param processing_method The processing method to get this location. 3361 */ 3362 public void setGpsProcessingMethod(String processing_method) { 3363 set(KEY_GPS_PROCESSING_METHOD, processing_method); 3364 } 3365 3366 /** 3367 * Removes GPS latitude, longitude, altitude, and timestamp from the 3368 * parameters. 3369 */ 3370 public void removeGpsData() { 3371 remove(KEY_GPS_LATITUDE); 3372 remove(KEY_GPS_LONGITUDE); 3373 remove(KEY_GPS_ALTITUDE); 3374 remove(KEY_GPS_TIMESTAMP); 3375 remove(KEY_GPS_PROCESSING_METHOD); 3376 } 3377 3378 /** 3379 * Gets the current white balance setting. 3380 * 3381 * @return current white balance. null if white balance setting is not 3382 * supported. 3383 * @see #WHITE_BALANCE_AUTO 3384 * @see #WHITE_BALANCE_INCANDESCENT 3385 * @see #WHITE_BALANCE_FLUORESCENT 3386 * @see #WHITE_BALANCE_WARM_FLUORESCENT 3387 * @see #WHITE_BALANCE_DAYLIGHT 3388 * @see #WHITE_BALANCE_CLOUDY_DAYLIGHT 3389 * @see #WHITE_BALANCE_TWILIGHT 3390 * @see #WHITE_BALANCE_SHADE 3391 * 3392 */ 3393 public String getWhiteBalance() { 3394 return get(KEY_WHITE_BALANCE); 3395 } 3396 3397 /** 3398 * Sets the white balance. Changing the setting will release the 3399 * auto-white balance lock. It is recommended not to change white 3400 * balance and AWB lock at the same time. 3401 * 3402 * @param value new white balance. 3403 * @see #getWhiteBalance() 3404 * @see #setAutoWhiteBalanceLock(boolean) 3405 */ 3406 public void setWhiteBalance(String value) { 3407 String oldValue = get(KEY_WHITE_BALANCE); 3408 if (same(value, oldValue)) return; 3409 set(KEY_WHITE_BALANCE, value); 3410 set(KEY_AUTO_WHITEBALANCE_LOCK, FALSE); 3411 } 3412 3413 /** 3414 * Gets the supported white balance. 3415 * 3416 * @return a list of supported white balance. null if white balance 3417 * setting is not supported. 3418 * @see #getWhiteBalance() 3419 */ 3420 public List<String> getSupportedWhiteBalance() { 3421 String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX); 3422 return split(str); 3423 } 3424 3425 /** 3426 * Gets the current color effect setting. 3427 * 3428 * @return current color effect. null if color effect 3429 * setting is not supported. 3430 * @see #EFFECT_NONE 3431 * @see #EFFECT_MONO 3432 * @see #EFFECT_NEGATIVE 3433 * @see #EFFECT_SOLARIZE 3434 * @see #EFFECT_SEPIA 3435 * @see #EFFECT_POSTERIZE 3436 * @see #EFFECT_WHITEBOARD 3437 * @see #EFFECT_BLACKBOARD 3438 * @see #EFFECT_AQUA 3439 */ 3440 public String getColorEffect() { 3441 return get(KEY_EFFECT); 3442 } 3443 3444 /** 3445 * Sets the current color effect setting. 3446 * 3447 * @param value new color effect. 3448 * @see #getColorEffect() 3449 */ 3450 public void setColorEffect(String value) { 3451 set(KEY_EFFECT, value); 3452 } 3453 3454 /** 3455 * Gets the supported color effects. 3456 * 3457 * @return a list of supported color effects. null if color effect 3458 * setting is not supported. 3459 * @see #getColorEffect() 3460 */ 3461 public List<String> getSupportedColorEffects() { 3462 String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX); 3463 return split(str); 3464 } 3465 3466 3467 /** 3468 * Gets the current antibanding setting. 3469 * 3470 * @return current antibanding. null if antibanding setting is not 3471 * supported. 3472 * @see #ANTIBANDING_AUTO 3473 * @see #ANTIBANDING_50HZ 3474 * @see #ANTIBANDING_60HZ 3475 * @see #ANTIBANDING_OFF 3476 */ 3477 public String getAntibanding() { 3478 return get(KEY_ANTIBANDING); 3479 } 3480 3481 /** 3482 * Sets the antibanding. 3483 * 3484 * @param antibanding new antibanding value. 3485 * @see #getAntibanding() 3486 */ 3487 public void setAntibanding(String antibanding) { 3488 set(KEY_ANTIBANDING, antibanding); 3489 } 3490 3491 /** 3492 * Gets the supported antibanding values. 3493 * 3494 * @return a list of supported antibanding values. null if antibanding 3495 * setting is not supported. 3496 * @see #getAntibanding() 3497 */ 3498 public List<String> getSupportedAntibanding() { 3499 String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX); 3500 return split(str); 3501 } 3502 3503 /** 3504 * Gets the current scene mode setting. 3505 * 3506 * @return one of SCENE_MODE_XXX string constant. null if scene mode 3507 * setting is not supported. 3508 * @see #SCENE_MODE_AUTO 3509 * @see #SCENE_MODE_ACTION 3510 * @see #SCENE_MODE_PORTRAIT 3511 * @see #SCENE_MODE_LANDSCAPE 3512 * @see #SCENE_MODE_NIGHT 3513 * @see #SCENE_MODE_NIGHT_PORTRAIT 3514 * @see #SCENE_MODE_THEATRE 3515 * @see #SCENE_MODE_BEACH 3516 * @see #SCENE_MODE_SNOW 3517 * @see #SCENE_MODE_SUNSET 3518 * @see #SCENE_MODE_STEADYPHOTO 3519 * @see #SCENE_MODE_FIREWORKS 3520 * @see #SCENE_MODE_SPORTS 3521 * @see #SCENE_MODE_PARTY 3522 * @see #SCENE_MODE_CANDLELIGHT 3523 * @see #SCENE_MODE_BARCODE 3524 */ 3525 public String getSceneMode() { 3526 return get(KEY_SCENE_MODE); 3527 } 3528 3529 /** 3530 * Sets the scene mode. Changing scene mode may override other 3531 * parameters (such as flash mode, focus mode, white balance). For 3532 * example, suppose originally flash mode is on and supported flash 3533 * modes are on/off. In night scene mode, both flash mode and supported 3534 * flash mode may be changed to off. After setting scene mode, 3535 * applications should call getParameters to know if some parameters are 3536 * changed. 3537 * 3538 * @param value scene mode. 3539 * @see #getSceneMode() 3540 */ 3541 public void setSceneMode(String value) { 3542 set(KEY_SCENE_MODE, value); 3543 } 3544 3545 /** 3546 * Gets the supported scene modes. 3547 * 3548 * @return a list of supported scene modes. null if scene mode setting 3549 * is not supported. 3550 * @see #getSceneMode() 3551 */ 3552 public List<String> getSupportedSceneModes() { 3553 String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX); 3554 return split(str); 3555 } 3556 3557 /** 3558 * Gets the current flash mode setting. 3559 * 3560 * @return current flash mode. null if flash mode setting is not 3561 * supported. 3562 * @see #FLASH_MODE_OFF 3563 * @see #FLASH_MODE_AUTO 3564 * @see #FLASH_MODE_ON 3565 * @see #FLASH_MODE_RED_EYE 3566 * @see #FLASH_MODE_TORCH 3567 */ 3568 public String getFlashMode() { 3569 return get(KEY_FLASH_MODE); 3570 } 3571 3572 /** 3573 * Sets the flash mode. 3574 * 3575 * @param value flash mode. 3576 * @see #getFlashMode() 3577 */ 3578 public void setFlashMode(String value) { 3579 set(KEY_FLASH_MODE, value); 3580 } 3581 3582 /** 3583 * Gets the supported flash modes. 3584 * 3585 * @return a list of supported flash modes. null if flash mode setting 3586 * is not supported. 3587 * @see #getFlashMode() 3588 */ 3589 public List<String> getSupportedFlashModes() { 3590 String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX); 3591 return split(str); 3592 } 3593 3594 /** 3595 * Gets the current focus mode setting. 3596 * 3597 * @return current focus mode. This method will always return a non-null 3598 * value. Applications should call {@link 3599 * #autoFocus(AutoFocusCallback)} to start the focus if focus 3600 * mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO. 3601 * @see #FOCUS_MODE_AUTO 3602 * @see #FOCUS_MODE_INFINITY 3603 * @see #FOCUS_MODE_MACRO 3604 * @see #FOCUS_MODE_FIXED 3605 * @see #FOCUS_MODE_EDOF 3606 * @see #FOCUS_MODE_CONTINUOUS_VIDEO 3607 */ 3608 public String getFocusMode() { 3609 return get(KEY_FOCUS_MODE); 3610 } 3611 3612 /** 3613 * Sets the focus mode. 3614 * 3615 * @param value focus mode. 3616 * @see #getFocusMode() 3617 */ 3618 public void setFocusMode(String value) { 3619 set(KEY_FOCUS_MODE, value); 3620 } 3621 3622 /** 3623 * Gets the supported focus modes. 3624 * 3625 * @return a list of supported focus modes. This method will always 3626 * return a list with at least one element. 3627 * @see #getFocusMode() 3628 */ 3629 public List<String> getSupportedFocusModes() { 3630 String str = get(KEY_FOCUS_MODE + SUPPORTED_VALUES_SUFFIX); 3631 return split(str); 3632 } 3633 3634 /** 3635 * Gets the focal length (in millimeter) of the camera. 3636 * 3637 * @return the focal length. Returns -1.0 when the device 3638 * doesn't report focal length information. 3639 */ 3640 public float getFocalLength() { 3641 return Float.parseFloat(get(KEY_FOCAL_LENGTH)); 3642 } 3643 3644 /** 3645 * Gets the horizontal angle of view in degrees. 3646 * 3647 * @return horizontal angle of view. Returns -1.0 when the device 3648 * doesn't report view angle information. 3649 */ 3650 public float getHorizontalViewAngle() { 3651 return Float.parseFloat(get(KEY_HORIZONTAL_VIEW_ANGLE)); 3652 } 3653 3654 /** 3655 * Gets the vertical angle of view in degrees. 3656 * 3657 * @return vertical angle of view. Returns -1.0 when the device 3658 * doesn't report view angle information. 3659 */ 3660 public float getVerticalViewAngle() { 3661 return Float.parseFloat(get(KEY_VERTICAL_VIEW_ANGLE)); 3662 } 3663 3664 /** 3665 * Gets the current exposure compensation index. 3666 * 3667 * @return current exposure compensation index. The range is {@link 3668 * #getMinExposureCompensation} to {@link 3669 * #getMaxExposureCompensation}. 0 means exposure is not 3670 * adjusted. 3671 */ 3672 public int getExposureCompensation() { 3673 return getInt(KEY_EXPOSURE_COMPENSATION, 0); 3674 } 3675 3676 /** 3677 * Sets the exposure compensation index. 3678 * 3679 * @param value exposure compensation index. The valid value range is 3680 * from {@link #getMinExposureCompensation} (inclusive) to {@link 3681 * #getMaxExposureCompensation} (inclusive). 0 means exposure is 3682 * not adjusted. Application should call 3683 * getMinExposureCompensation and getMaxExposureCompensation to 3684 * know if exposure compensation is supported. 3685 */ 3686 public void setExposureCompensation(int value) { 3687 set(KEY_EXPOSURE_COMPENSATION, value); 3688 } 3689 3690 /** 3691 * Gets the maximum exposure compensation index. 3692 * 3693 * @return maximum exposure compensation index (>=0). If both this 3694 * method and {@link #getMinExposureCompensation} return 0, 3695 * exposure compensation is not supported. 3696 */ 3697 public int getMaxExposureCompensation() { 3698 return getInt(KEY_MAX_EXPOSURE_COMPENSATION, 0); 3699 } 3700 3701 /** 3702 * Gets the minimum exposure compensation index. 3703 * 3704 * @return minimum exposure compensation index (<=0). If both this 3705 * method and {@link #getMaxExposureCompensation} return 0, 3706 * exposure compensation is not supported. 3707 */ 3708 public int getMinExposureCompensation() { 3709 return getInt(KEY_MIN_EXPOSURE_COMPENSATION, 0); 3710 } 3711 3712 /** 3713 * Gets the exposure compensation step. 3714 * 3715 * @return exposure compensation step. Applications can get EV by 3716 * multiplying the exposure compensation index and step. Ex: if 3717 * exposure compensation index is -6 and step is 0.333333333, EV 3718 * is -2. 3719 */ 3720 public float getExposureCompensationStep() { 3721 return getFloat(KEY_EXPOSURE_COMPENSATION_STEP, 0); 3722 } 3723 3724 /** 3725 * <p>Sets the auto-exposure lock state. Applications should check 3726 * {@link #isAutoExposureLockSupported} before using this method.</p> 3727 * 3728 * <p>If set to true, the camera auto-exposure routine will immediately 3729 * pause until the lock is set to false. Exposure compensation settings 3730 * changes will still take effect while auto-exposure is locked.</p> 3731 * 3732 * <p>If auto-exposure is already locked, setting this to true again has 3733 * no effect (the driver will not recalculate exposure values).</p> 3734 * 3735 * <p>Stopping preview with {@link #stopPreview()}, or triggering still 3736 * image capture with {@link #takePicture(Camera.ShutterCallback, 3737 * Camera.PictureCallback, Camera.PictureCallback)}, will not change the 3738 * lock.</p> 3739 * 3740 * <p>Exposure compensation, auto-exposure lock, and auto-white balance 3741 * lock can be used to capture an exposure-bracketed burst of images, 3742 * for example.</p> 3743 * 3744 * <p>Auto-exposure state, including the lock state, will not be 3745 * maintained after camera {@link #release()} is called. Locking 3746 * auto-exposure after {@link #open()} but before the first call to 3747 * {@link #startPreview()} will not allow the auto-exposure routine to 3748 * run at all, and may result in severely over- or under-exposed 3749 * images.</p> 3750 * 3751 * @param toggle new state of the auto-exposure lock. True means that 3752 * auto-exposure is locked, false means that the auto-exposure 3753 * routine is free to run normally. 3754 * 3755 * @see #getAutoExposureLock() 3756 */ 3757 public void setAutoExposureLock(boolean toggle) { 3758 set(KEY_AUTO_EXPOSURE_LOCK, toggle ? TRUE : FALSE); 3759 } 3760 3761 /** 3762 * Gets the state of the auto-exposure lock. Applications should check 3763 * {@link #isAutoExposureLockSupported} before using this method. See 3764 * {@link #setAutoExposureLock} for details about the lock. 3765 * 3766 * @return State of the auto-exposure lock. Returns true if 3767 * auto-exposure is currently locked, and false otherwise. 3768 * 3769 * @see #setAutoExposureLock(boolean) 3770 * 3771 */ 3772 public boolean getAutoExposureLock() { 3773 String str = get(KEY_AUTO_EXPOSURE_LOCK); 3774 return TRUE.equals(str); 3775 } 3776 3777 /** 3778 * Returns true if auto-exposure locking is supported. Applications 3779 * should call this before trying to lock auto-exposure. See 3780 * {@link #setAutoExposureLock} for details about the lock. 3781 * 3782 * @return true if auto-exposure lock is supported. 3783 * @see #setAutoExposureLock(boolean) 3784 * 3785 */ 3786 public boolean isAutoExposureLockSupported() { 3787 String str = get(KEY_AUTO_EXPOSURE_LOCK_SUPPORTED); 3788 return TRUE.equals(str); 3789 } 3790 3791 /** 3792 * <p>Sets the auto-white balance lock state. Applications should check 3793 * {@link #isAutoWhiteBalanceLockSupported} before using this 3794 * method.</p> 3795 * 3796 * <p>If set to true, the camera auto-white balance routine will 3797 * immediately pause until the lock is set to false.</p> 3798 * 3799 * <p>If auto-white balance is already locked, setting this to true 3800 * again has no effect (the driver will not recalculate white balance 3801 * values).</p> 3802 * 3803 * <p>Stopping preview with {@link #stopPreview()}, or triggering still 3804 * image capture with {@link #takePicture(Camera.ShutterCallback, 3805 * Camera.PictureCallback, Camera.PictureCallback)}, will not change the 3806 * the lock.</p> 3807 * 3808 * <p> Changing the white balance mode with {@link #setWhiteBalance} 3809 * will release the auto-white balance lock if it is set.</p> 3810 * 3811 * <p>Exposure compensation, AE lock, and AWB lock can be used to 3812 * capture an exposure-bracketed burst of images, for example. 3813 * Auto-white balance state, including the lock state, will not be 3814 * maintained after camera {@link #release()} is called. Locking 3815 * auto-white balance after {@link #open()} but before the first call to 3816 * {@link #startPreview()} will not allow the auto-white balance routine 3817 * to run at all, and may result in severely incorrect color in captured 3818 * images.</p> 3819 * 3820 * @param toggle new state of the auto-white balance lock. True means 3821 * that auto-white balance is locked, false means that the 3822 * auto-white balance routine is free to run normally. 3823 * 3824 * @see #getAutoWhiteBalanceLock() 3825 * @see #setWhiteBalance(String) 3826 */ 3827 public void setAutoWhiteBalanceLock(boolean toggle) { 3828 set(KEY_AUTO_WHITEBALANCE_LOCK, toggle ? TRUE : FALSE); 3829 } 3830 3831 /** 3832 * Gets the state of the auto-white balance lock. Applications should 3833 * check {@link #isAutoWhiteBalanceLockSupported} before using this 3834 * method. See {@link #setAutoWhiteBalanceLock} for details about the 3835 * lock. 3836 * 3837 * @return State of the auto-white balance lock. Returns true if 3838 * auto-white balance is currently locked, and false 3839 * otherwise. 3840 * 3841 * @see #setAutoWhiteBalanceLock(boolean) 3842 * 3843 */ 3844 public boolean getAutoWhiteBalanceLock() { 3845 String str = get(KEY_AUTO_WHITEBALANCE_LOCK); 3846 return TRUE.equals(str); 3847 } 3848 3849 /** 3850 * Returns true if auto-white balance locking is supported. Applications 3851 * should call this before trying to lock auto-white balance. See 3852 * {@link #setAutoWhiteBalanceLock} for details about the lock. 3853 * 3854 * @return true if auto-white balance lock is supported. 3855 * @see #setAutoWhiteBalanceLock(boolean) 3856 * 3857 */ 3858 public boolean isAutoWhiteBalanceLockSupported() { 3859 String str = get(KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED); 3860 return TRUE.equals(str); 3861 } 3862 3863 /** 3864 * Gets current zoom value. This also works when smooth zoom is in 3865 * progress. Applications should check {@link #isZoomSupported} before 3866 * using this method. 3867 * 3868 * @return the current zoom value. The range is 0 to {@link 3869 * #getMaxZoom}. 0 means the camera is not zoomed. 3870 */ 3871 public int getZoom() { 3872 return getInt(KEY_ZOOM, 0); 3873 } 3874 3875 /** 3876 * Sets current zoom value. If the camera is zoomed (value > 0), the 3877 * actual picture size may be smaller than picture size setting. 3878 * Applications can check the actual picture size after picture is 3879 * returned from {@link PictureCallback}. The preview size remains the 3880 * same in zoom. Applications should check {@link #isZoomSupported} 3881 * before using this method. 3882 * 3883 * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}. 3884 */ 3885 public void setZoom(int value) { 3886 set(KEY_ZOOM, value); 3887 } 3888 3889 /** 3890 * Returns true if zoom is supported. Applications should call this 3891 * before using other zoom methods. 3892 * 3893 * @return true if zoom is supported. 3894 */ 3895 public boolean isZoomSupported() { 3896 String str = get(KEY_ZOOM_SUPPORTED); 3897 return TRUE.equals(str); 3898 } 3899 3900 /** 3901 * Gets the maximum zoom value allowed for snapshot. This is the maximum 3902 * value that applications can set to {@link #setZoom(int)}. 3903 * Applications should call {@link #isZoomSupported} before using this 3904 * method. This value may change in different preview size. Applications 3905 * should call this again after setting preview size. 3906 * 3907 * @return the maximum zoom value supported by the camera. 3908 */ 3909 public int getMaxZoom() { 3910 return getInt(KEY_MAX_ZOOM, 0); 3911 } 3912 3913 /** 3914 * Gets the zoom ratios of all zoom values. Applications should check 3915 * {@link #isZoomSupported} before using this method. 3916 * 3917 * @return the zoom ratios in 1/100 increments. Ex: a zoom of 3.2x is 3918 * returned as 320. The number of elements is {@link 3919 * #getMaxZoom} + 1. The list is sorted from small to large. The 3920 * first element is always 100. The last element is the zoom 3921 * ratio of the maximum zoom value. 3922 */ 3923 public List<Integer> getZoomRatios() { 3924 return splitInt(get(KEY_ZOOM_RATIOS)); 3925 } 3926 3927 /** 3928 * Returns true if smooth zoom is supported. Applications should call 3929 * this before using other smooth zoom methods. 3930 * 3931 * @return true if smooth zoom is supported. 3932 */ 3933 public boolean isSmoothZoomSupported() { 3934 String str = get(KEY_SMOOTH_ZOOM_SUPPORTED); 3935 return TRUE.equals(str); 3936 } 3937 3938 /** 3939 * <p>Gets the distances from the camera to where an object appears to be 3940 * in focus. The object is sharpest at the optimal focus distance. The 3941 * depth of field is the far focus distance minus near focus distance.</p> 3942 * 3943 * <p>Focus distances may change after calling {@link 3944 * #autoFocus(AutoFocusCallback)}, {@link #cancelAutoFocus}, or {@link 3945 * #startPreview()}. Applications can call {@link #getParameters()} 3946 * and this method anytime to get the latest focus distances. If the 3947 * focus mode is FOCUS_MODE_CONTINUOUS_VIDEO, focus distances may change 3948 * from time to time.</p> 3949 * 3950 * <p>This method is intended to estimate the distance between the camera 3951 * and the subject. After autofocus, the subject distance may be within 3952 * near and far focus distance. However, the precision depends on the 3953 * camera hardware, autofocus algorithm, the focus area, and the scene. 3954 * The error can be large and it should be only used as a reference.</p> 3955 * 3956 * <p>Far focus distance >= optimal focus distance >= near focus distance. 3957 * If the focus distance is infinity, the value will be 3958 * {@code Float.POSITIVE_INFINITY}.</p> 3959 * 3960 * @param output focus distances in meters. output must be a float 3961 * array with three elements. Near focus distance, optimal focus 3962 * distance, and far focus distance will be filled in the array. 3963 * @see #FOCUS_DISTANCE_NEAR_INDEX 3964 * @see #FOCUS_DISTANCE_OPTIMAL_INDEX 3965 * @see #FOCUS_DISTANCE_FAR_INDEX 3966 */ 3967 public void getFocusDistances(float[] output) { 3968 if (output == null || output.length != 3) { 3969 throw new IllegalArgumentException( 3970 "output must be a float array with three elements."); 3971 } 3972 splitFloat(get(KEY_FOCUS_DISTANCES), output); 3973 } 3974 3975 /** 3976 * Gets the maximum number of focus areas supported. This is the maximum 3977 * length of the list in {@link #setFocusAreas(List)} and 3978 * {@link #getFocusAreas()}. 3979 * 3980 * @return the maximum number of focus areas supported by the camera. 3981 * @see #getFocusAreas() 3982 */ 3983 public int getMaxNumFocusAreas() { 3984 return getInt(KEY_MAX_NUM_FOCUS_AREAS, 0); 3985 } 3986 3987 /** 3988 * <p>Gets the current focus areas. Camera driver uses the areas to decide 3989 * focus.</p> 3990 * 3991 * <p>Before using this API or {@link #setFocusAreas(List)}, apps should 3992 * call {@link #getMaxNumFocusAreas()} to know the maximum number of 3993 * focus areas first. If the value is 0, focus area is not supported.</p> 3994 * 3995 * <p>Each focus area is a rectangle with specified weight. The direction 3996 * is relative to the sensor orientation, that is, what the sensor sees. 3997 * The direction is not affected by the rotation or mirroring of 3998 * {@link #setDisplayOrientation(int)}. Coordinates of the rectangle 3999 * range from -1000 to 1000. (-1000, -1000) is the upper left point. 4000 * (1000, 1000) is the lower right point. The width and height of focus 4001 * areas cannot be 0 or negative.</p> 4002 * 4003 * <p>The weight must range from 1 to 1000. The weight should be 4004 * interpreted as a per-pixel weight - all pixels in the area have the 4005 * specified weight. This means a small area with the same weight as a 4006 * larger area will have less influence on the focusing than the larger 4007 * area. Focus areas can partially overlap and the driver will add the 4008 * weights in the overlap region.</p> 4009 * 4010 * <p>A special case of a {@code null} focus area list means the driver is 4011 * free to select focus targets as it wants. For example, the driver may 4012 * use more signals to select focus areas and change them 4013 * dynamically. Apps can set the focus area list to {@code null} if they 4014 * want the driver to completely control focusing.</p> 4015 * 4016 * <p>Focus areas are relative to the current field of view 4017 * ({@link #getZoom()}). No matter what the zoom level is, (-1000,-1000) 4018 * represents the top of the currently visible camera frame. The focus 4019 * area cannot be set to be outside the current field of view, even 4020 * when using zoom.</p> 4021 * 4022 * <p>Focus area only has effect if the current focus mode is 4023 * {@link #FOCUS_MODE_AUTO}, {@link #FOCUS_MODE_MACRO}, 4024 * {@link #FOCUS_MODE_CONTINUOUS_VIDEO}, or 4025 * {@link #FOCUS_MODE_CONTINUOUS_PICTURE}.</p> 4026 * 4027 * @return a list of current focus areas 4028 */ 4029 public List<Area> getFocusAreas() { 4030 return splitArea(get(KEY_FOCUS_AREAS)); 4031 } 4032 4033 /** 4034 * Sets focus areas. See {@link #getFocusAreas()} for documentation. 4035 * 4036 * @param focusAreas the focus areas 4037 * @see #getFocusAreas() 4038 */ 4039 public void setFocusAreas(List<Area> focusAreas) { 4040 set(KEY_FOCUS_AREAS, focusAreas); 4041 } 4042 4043 /** 4044 * Gets the maximum number of metering areas supported. This is the 4045 * maximum length of the list in {@link #setMeteringAreas(List)} and 4046 * {@link #getMeteringAreas()}. 4047 * 4048 * @return the maximum number of metering areas supported by the camera. 4049 * @see #getMeteringAreas() 4050 */ 4051 public int getMaxNumMeteringAreas() { 4052 return getInt(KEY_MAX_NUM_METERING_AREAS, 0); 4053 } 4054 4055 /** 4056 * <p>Gets the current metering areas. Camera driver uses these areas to 4057 * decide exposure.</p> 4058 * 4059 * <p>Before using this API or {@link #setMeteringAreas(List)}, apps should 4060 * call {@link #getMaxNumMeteringAreas()} to know the maximum number of 4061 * metering areas first. If the value is 0, metering area is not 4062 * supported.</p> 4063 * 4064 * <p>Each metering area is a rectangle with specified weight. The 4065 * direction is relative to the sensor orientation, that is, what the 4066 * sensor sees. The direction is not affected by the rotation or 4067 * mirroring of {@link #setDisplayOrientation(int)}. Coordinates of the 4068 * rectangle range from -1000 to 1000. (-1000, -1000) is the upper left 4069 * point. (1000, 1000) is the lower right point. The width and height of 4070 * metering areas cannot be 0 or negative.</p> 4071 * 4072 * <p>The weight must range from 1 to 1000, and represents a weight for 4073 * every pixel in the area. This means that a large metering area with 4074 * the same weight as a smaller area will have more effect in the 4075 * metering result. Metering areas can partially overlap and the driver 4076 * will add the weights in the overlap region.</p> 4077 * 4078 * <p>A special case of a {@code null} metering area list means the driver 4079 * is free to meter as it chooses. For example, the driver may use more 4080 * signals to select metering areas and change them dynamically. Apps 4081 * can set the metering area list to {@code null} if they want the 4082 * driver to completely control metering.</p> 4083 * 4084 * <p>Metering areas are relative to the current field of view 4085 * ({@link #getZoom()}). No matter what the zoom level is, (-1000,-1000) 4086 * represents the top of the currently visible camera frame. The 4087 * metering area cannot be set to be outside the current field of view, 4088 * even when using zoom.</p> 4089 * 4090 * <p>No matter what metering areas are, the final exposure are compensated 4091 * by {@link #setExposureCompensation(int)}.</p> 4092 * 4093 * @return a list of current metering areas 4094 */ 4095 public List<Area> getMeteringAreas() { 4096 return splitArea(get(KEY_METERING_AREAS)); 4097 } 4098 4099 /** 4100 * Sets metering areas. See {@link #getMeteringAreas()} for 4101 * documentation. 4102 * 4103 * @param meteringAreas the metering areas 4104 * @see #getMeteringAreas() 4105 */ 4106 public void setMeteringAreas(List<Area> meteringAreas) { 4107 set(KEY_METERING_AREAS, meteringAreas); 4108 } 4109 4110 /** 4111 * Gets the maximum number of detected faces supported. This is the 4112 * maximum length of the list returned from {@link FaceDetectionListener}. 4113 * If the return value is 0, face detection of the specified type is not 4114 * supported. 4115 * 4116 * @return the maximum number of detected face supported by the camera. 4117 * @see #startFaceDetection() 4118 */ 4119 public int getMaxNumDetectedFaces() { 4120 return getInt(KEY_MAX_NUM_DETECTED_FACES_HW, 0); 4121 } 4122 4123 /** 4124 * Sets recording mode hint. This tells the camera that the intent of 4125 * the application is to record videos {@link 4126 * android.media.MediaRecorder#start()}, not to take still pictures 4127 * {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, 4128 * Camera.PictureCallback, Camera.PictureCallback)}. Using this hint can 4129 * allow MediaRecorder.start() to start faster or with fewer glitches on 4130 * output. This should be called before starting preview for the best 4131 * result, but can be changed while the preview is active. The default 4132 * value is false. 4133 * 4134 * The app can still call takePicture() when the hint is true or call 4135 * MediaRecorder.start() when the hint is false. But the performance may 4136 * be worse. 4137 * 4138 * @param hint true if the apps intend to record videos using 4139 * {@link android.media.MediaRecorder}. 4140 */ 4141 public void setRecordingHint(boolean hint) { 4142 set(KEY_RECORDING_HINT, hint ? TRUE : FALSE); 4143 } 4144 4145 /** 4146 * <p>Returns true if video snapshot is supported. That is, applications 4147 * can call {@link #takePicture(Camera.ShutterCallback, 4148 * Camera.PictureCallback, Camera.PictureCallback, 4149 * Camera.PictureCallback)} during recording. Applications do not need 4150 * to call {@link #startPreview()} after taking a picture. The preview 4151 * will be still active. Other than that, taking a picture during 4152 * recording is identical to taking a picture normally. All settings and 4153 * methods related to takePicture work identically. Ex: 4154 * {@link #getPictureSize()}, {@link #getSupportedPictureSizes()}, 4155 * {@link #setJpegQuality(int)}, {@link #setRotation(int)}, and etc. The 4156 * picture will have an EXIF header. {@link #FLASH_MODE_AUTO} and 4157 * {@link #FLASH_MODE_ON} also still work, but the video will record the 4158 * flash.</p> 4159 * 4160 * <p>Applications can set shutter callback as null to avoid the shutter 4161 * sound. It is also recommended to set raw picture and post view 4162 * callbacks to null to avoid the interrupt of preview display.</p> 4163 * 4164 * <p>Field-of-view of the recorded video may be different from that of the 4165 * captured pictures. The maximum size of a video snapshot may be 4166 * smaller than that for regular still captures. If the current picture 4167 * size is set higher than can be supported by video snapshot, the 4168 * picture will be captured at the maximum supported size instead.</p> 4169 * 4170 * @return true if video snapshot is supported. 4171 */ 4172 public boolean isVideoSnapshotSupported() { 4173 String str = get(KEY_VIDEO_SNAPSHOT_SUPPORTED); 4174 return TRUE.equals(str); 4175 } 4176 4177 /** 4178 * <p>Enables and disables video stabilization. Use 4179 * {@link #isVideoStabilizationSupported} to determine if calling this 4180 * method is valid.</p> 4181 * 4182 * <p>Video stabilization reduces the shaking due to the motion of the 4183 * camera in both the preview stream and in recorded videos, including 4184 * data received from the preview callback. It does not reduce motion 4185 * blur in images captured with 4186 * {@link Camera#takePicture takePicture}.</p> 4187 * 4188 * <p>Video stabilization can be enabled and disabled while preview or 4189 * recording is active, but toggling it may cause a jump in the video 4190 * stream that may be undesirable in a recorded video.</p> 4191 * 4192 * @param toggle Set to true to enable video stabilization, and false to 4193 * disable video stabilization. 4194 * @see #isVideoStabilizationSupported() 4195 * @see #getVideoStabilization() 4196 */ 4197 public void setVideoStabilization(boolean toggle) { 4198 set(KEY_VIDEO_STABILIZATION, toggle ? TRUE : FALSE); 4199 } 4200 4201 /** 4202 * Get the current state of video stabilization. See 4203 * {@link #setVideoStabilization} for details of video stabilization. 4204 * 4205 * @return true if video stabilization is enabled 4206 * @see #isVideoStabilizationSupported() 4207 * @see #setVideoStabilization(boolean) 4208 */ 4209 public boolean getVideoStabilization() { 4210 String str = get(KEY_VIDEO_STABILIZATION); 4211 return TRUE.equals(str); 4212 } 4213 4214 /** 4215 * Returns true if video stabilization is supported. See 4216 * {@link #setVideoStabilization} for details of video stabilization. 4217 * 4218 * @return true if video stabilization is supported 4219 * @see #setVideoStabilization(boolean) 4220 * @see #getVideoStabilization() 4221 */ 4222 public boolean isVideoStabilizationSupported() { 4223 String str = get(KEY_VIDEO_STABILIZATION_SUPPORTED); 4224 return TRUE.equals(str); 4225 } 4226 4227 // Splits a comma delimited string to an ArrayList of String. 4228 // Return null if the passing string is null or the size is 0. 4229 private ArrayList<String> split(String str) { 4230 if (str == null) return null; 4231 4232 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4233 splitter.setString(str); 4234 ArrayList<String> substrings = new ArrayList<String>(); 4235 for (String s : splitter) { 4236 substrings.add(s); 4237 } 4238 return substrings; 4239 } 4240 4241 // Splits a comma delimited string to an ArrayList of Integer. 4242 // Return null if the passing string is null or the size is 0. 4243 private ArrayList<Integer> splitInt(String str) { 4244 if (str == null) return null; 4245 4246 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4247 splitter.setString(str); 4248 ArrayList<Integer> substrings = new ArrayList<Integer>(); 4249 for (String s : splitter) { 4250 substrings.add(Integer.parseInt(s)); 4251 } 4252 if (substrings.size() == 0) return null; 4253 return substrings; 4254 } 4255 4256 private void splitInt(String str, int[] output) { 4257 if (str == null) return; 4258 4259 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4260 splitter.setString(str); 4261 int index = 0; 4262 for (String s : splitter) { 4263 output[index++] = Integer.parseInt(s); 4264 } 4265 } 4266 4267 // Splits a comma delimited string to an ArrayList of Float. 4268 private void splitFloat(String str, float[] output) { 4269 if (str == null) return; 4270 4271 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4272 splitter.setString(str); 4273 int index = 0; 4274 for (String s : splitter) { 4275 output[index++] = Float.parseFloat(s); 4276 } 4277 } 4278 4279 // Returns the value of a float parameter. 4280 private float getFloat(String key, float defaultValue) { 4281 try { 4282 return Float.parseFloat(mMap.get(key)); 4283 } catch (NumberFormatException ex) { 4284 return defaultValue; 4285 } 4286 } 4287 4288 // Returns the value of a integer parameter. 4289 private int getInt(String key, int defaultValue) { 4290 try { 4291 return Integer.parseInt(mMap.get(key)); 4292 } catch (NumberFormatException ex) { 4293 return defaultValue; 4294 } 4295 } 4296 4297 // Splits a comma delimited string to an ArrayList of Size. 4298 // Return null if the passing string is null or the size is 0. 4299 private ArrayList<Size> splitSize(String str) { 4300 if (str == null) return null; 4301 4302 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4303 splitter.setString(str); 4304 ArrayList<Size> sizeList = new ArrayList<Size>(); 4305 for (String s : splitter) { 4306 Size size = strToSize(s); 4307 if (size != null) sizeList.add(size); 4308 } 4309 if (sizeList.size() == 0) return null; 4310 return sizeList; 4311 } 4312 4313 // Parses a string (ex: "480x320") to Size object. 4314 // Return null if the passing string is null. 4315 private Size strToSize(String str) { 4316 if (str == null) return null; 4317 4318 int pos = str.indexOf('x'); 4319 if (pos != -1) { 4320 String width = str.substring(0, pos); 4321 String height = str.substring(pos + 1); 4322 return new Size(Integer.parseInt(width), 4323 Integer.parseInt(height)); 4324 } 4325 Log.e(TAG, "Invalid size parameter string=" + str); 4326 return null; 4327 } 4328 4329 // Splits a comma delimited string to an ArrayList of int array. 4330 // Example string: "(10000,26623),(10000,30000)". Return null if the 4331 // passing string is null or the size is 0. 4332 private ArrayList<int[]> splitRange(String str) { 4333 if (str == null || str.charAt(0) != '(' 4334 || str.charAt(str.length() - 1) != ')') { 4335 Log.e(TAG, "Invalid range list string=" + str); 4336 return null; 4337 } 4338 4339 ArrayList<int[]> rangeList = new ArrayList<int[]>(); 4340 int endIndex, fromIndex = 1; 4341 do { 4342 int[] range = new int[2]; 4343 endIndex = str.indexOf("),(", fromIndex); 4344 if (endIndex == -1) endIndex = str.length() - 1; 4345 splitInt(str.substring(fromIndex, endIndex), range); 4346 rangeList.add(range); 4347 fromIndex = endIndex + 3; 4348 } while (endIndex != str.length() - 1); 4349 4350 if (rangeList.size() == 0) return null; 4351 return rangeList; 4352 } 4353 4354 // Splits a comma delimited string to an ArrayList of Area objects. 4355 // Example string: "(-10,-10,0,0,300),(0,0,10,10,700)". Return null if 4356 // the passing string is null or the size is 0 or (0,0,0,0,0). 4357 private ArrayList<Area> splitArea(String str) { 4358 if (str == null || str.charAt(0) != '(' 4359 || str.charAt(str.length() - 1) != ')') { 4360 Log.e(TAG, "Invalid area string=" + str); 4361 return null; 4362 } 4363 4364 ArrayList<Area> result = new ArrayList<Area>(); 4365 int endIndex, fromIndex = 1; 4366 int[] array = new int[5]; 4367 do { 4368 endIndex = str.indexOf("),(", fromIndex); 4369 if (endIndex == -1) endIndex = str.length() - 1; 4370 splitInt(str.substring(fromIndex, endIndex), array); 4371 Rect rect = new Rect(array[0], array[1], array[2], array[3]); 4372 result.add(new Area(rect, array[4])); 4373 fromIndex = endIndex + 3; 4374 } while (endIndex != str.length() - 1); 4375 4376 if (result.size() == 0) return null; 4377 4378 if (result.size() == 1) { 4379 Area area = result.get(0); 4380 Rect rect = area.rect; 4381 if (rect.left == 0 && rect.top == 0 && rect.right == 0 4382 && rect.bottom == 0 && area.weight == 0) { 4383 return null; 4384 } 4385 } 4386 4387 return result; 4388 } 4389 4390 private boolean same(String s1, String s2) { 4391 if (s1 == null && s2 == null) return true; 4392 if (s1 != null && s1.equals(s2)) return true; 4393 return false; 4394 } 4395 }; 4396} 4397