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