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