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