FileDocCategorySizeDatePackage
Camera.javaAPI DocAndroid 5.1 API175841Thu Mar 12 22:22:10 GMT 2015android.hardware

Camera

public class Camera extends Object
The Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. This class is a client for the Camera service, which manages the actual camera hardware.

To access the device camera, you must declare the {@link android.Manifest.permission#CAMERA} permission in your Android Manifest. Also be sure to include the <uses-feature> manifest element to declare camera features used by your application. For example, if you use the camera and auto-focus feature, your Manifest should include the following:

 <uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

To take pictures with this class, use the following steps:

  1. Obtain an instance of Camera from {@link #open(int)}.
  2. Get existing (default) settings with {@link #getParameters()}.
  3. If necessary, modify the returned {@link Camera.Parameters} object and call {@link #setParameters(Camera.Parameters)}.
  4. If desired, call {@link #setDisplayOrientation(int)}.
  5. Important: Pass a fully initialized {@link SurfaceHolder} to {@link #setPreviewDisplay(SurfaceHolder)}. Without a surface, the camera will be unable to start the preview.
  6. Important: Call {@link #startPreview()} to start updating the preview surface. Preview must be started before you can take a picture.
  7. When you want, call {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)} to capture a photo. Wait for the callbacks to provide the actual image data.
  8. After taking a picture, preview display will have stopped. To take more photos, call {@link #startPreview()} again first.
  9. Call {@link #stopPreview()} to stop updating the preview surface.
  10. Important: Call {@link #release()} to release the camera for use by other applications. Applications should release the camera immediately in {@link android.app.Activity#onPause()} (and re-{@link #open()} it in {@link android.app.Activity#onResume()}).

To quickly switch to video recording mode, use these steps:

  1. Obtain and initialize a Camera and start preview as described above.
  2. Call {@link #unlock()} to allow the media process to access the camera.
  3. Pass the camera to {@link android.media.MediaRecorder#setCamera(Camera)}. See {@link android.media.MediaRecorder} information about video recording.
  4. When finished recording, call {@link #reconnect()} to re-acquire and re-lock the camera.
  5. If desired, restart preview and take more photos or videos.
  6. Call {@link #stopPreview()} and {@link #release()} as described above.

This class is not thread-safe, and is meant for use from one event thread. Most long-running operations (preview, focus, photo capture, etc) happen asynchronously and invoke callbacks as necessary. Callbacks will be invoked on the event thread {@link #open(int)} was called from. This class's methods must never be called from multiple threads at once.

Caution: Different Android-powered devices may have different hardware specifications, such as megapixel ratings and auto-focus capabilities. In order for your application to be compatible with more devices, you should not make assumptions about the device camera specifications.

Developer Guides

For more information about using cameras, read the Camera developer guide.

deprecated
We recommend using the new {@link android.hardware.camera2} API for new applications.

Fields Summary
private static final String
TAG
private static final int
CAMERA_MSG_ERROR
private static final int
CAMERA_MSG_SHUTTER
private static final int
CAMERA_MSG_FOCUS
private static final int
CAMERA_MSG_ZOOM
private static final int
CAMERA_MSG_PREVIEW_FRAME
private static final int
CAMERA_MSG_VIDEO_FRAME
private static final int
CAMERA_MSG_POSTVIEW_FRAME
private static final int
CAMERA_MSG_RAW_IMAGE
private static final int
CAMERA_MSG_COMPRESSED_IMAGE
private static final int
CAMERA_MSG_RAW_IMAGE_NOTIFY
private static final int
CAMERA_MSG_PREVIEW_METADATA
private static final int
CAMERA_MSG_FOCUS_MOVE
private long
mNativeContext
private EventHandler
mEventHandler
private ShutterCallback
mShutterCallback
private PictureCallback
mRawImageCallback
private PictureCallback
mJpegCallback
private PreviewCallback
mPreviewCallback
private boolean
mUsingPreviewAllocation
private PictureCallback
mPostviewCallback
private AutoFocusCallback
mAutoFocusCallback
private AutoFocusMoveCallback
mAutoFocusMoveCallback
private OnZoomChangeListener
mZoomListener
private FaceDetectionListener
mFaceListener
private ErrorCallback
mErrorCallback
private boolean
mOneShot
private boolean
mWithBuffer
private boolean
mFaceDetectionRunning
private final Object
mAutoFocusCallbackLock
private static final int
NO_ERROR
private static final int
EACCESS
private static final int
ENODEV
private static final int
EBUSY
private static final int
EINVAL
private static final int
ENOSYS
private static final int
EUSERS
private static final int
EOPNOTSUPP
public static final String
ACTION_NEW_PICTURE
Broadcast Action: A new picture is taken by the camera, and the entry of the picture has been added to the media store. {@link android.content.Intent#getData} is URI of the picture.
public static final String
ACTION_NEW_VIDEO
Broadcast Action: A new video is recorded by the camera, and the entry of the video has been added to the media store. {@link android.content.Intent#getData} is URI of the video.
public static final int
CAMERA_HAL_API_VERSION_1_0
Camera HAL device API version 1.0
private static final int
CAMERA_HAL_API_VERSION_NORMAL_CONNECT
A constant meaning the normal camera connect/open will be used.
private static final int
CAMERA_HAL_API_VERSION_UNSPECIFIED
Used to indicate HAL version un-specified.
private static final int
CAMERA_FACE_DETECTION_HW
Hardware face detection. It does not use much CPU.
private static final int
CAMERA_FACE_DETECTION_SW
Software face detection. It uses some CPU.
public static final int
CAMERA_ERROR_UNKNOWN
Unspecified camera error.
public static final int
CAMERA_ERROR_SERVER_DIED
Media server died. In this case, the application must release the Camera object and instantiate a new one.
Constructors Summary
Camera(int cameraId)
used by Camera#open, Camera#open(int)

        int err = cameraInitNormal(cameraId);
        if (checkInitErrors(err)) {
            switch(err) {
                case EACCESS:
                    throw new RuntimeException("Fail to connect to camera service");
                case ENODEV:
                    throw new RuntimeException("Camera initialization failed");
                default:
                    // Should never hit this.
                    throw new RuntimeException("Unknown camera error");
            }
        }
    
Camera()
An empty Camera for testing purpose.

    
private Camera(int cameraId, int halVersion)
Create a legacy camera object.

param
cameraId The hardware camera to access, between 0 and {@link #getNumberOfCameras()}-1.
param
halVersion The HAL API version this camera device to be opened as.

        int err = cameraInitVersion(cameraId, halVersion);
        if (checkInitErrors(err)) {
            switch(err) {
                case EACCESS:
                    throw new RuntimeException("Fail to connect to camera service");
                case ENODEV:
                    throw new RuntimeException("Camera initialization failed");
                case ENOSYS:
                    throw new RuntimeException("Camera initialization failed because some methods"
                            + " are not implemented");
                case EOPNOTSUPP:
                    throw new RuntimeException("Camera initialization failed because the hal"
                            + " version is not supported by this device");
                case EINVAL:
                    throw new RuntimeException("Camera initialization failed because the input"
                            + " arugments are invalid");
                case EBUSY:
                    throw new RuntimeException("Camera initialization failed because the camera"
                            + " device was already opened");
                case EUSERS:
                    throw new RuntimeException("Camera initialization failed because the max"
                            + " number of camera devices were already opened");
                default:
                    // Should never hit this.
                    throw new RuntimeException("Unknown camera error");
            }
        }
    
Methods Summary
private final native void_addCallbackBuffer(byte[] callbackBuffer, int msgType)

private final native boolean_enableShutterSound(boolean enabled)

private static native void_getCameraInfo(int cameraId, android.hardware.Camera$CameraInfo cameraInfo)

private final native void_startFaceDetection(int type)

private final native void_stopFaceDetection()

private final native void_stopPreview()

public final voidaddCallbackBuffer(byte[] callbackBuffer)
Adds a pre-allocated buffer to the preview callback buffer queue. Applications can add one or more buffers to the queue. When a preview frame arrives and there is still at least one available buffer, the buffer will be used and removed from the queue. Then preview callback is invoked with the buffer. If a frame arrives and there is no buffer left, the frame is discarded. Applications should add buffers back when they finish processing the data in them.

For formats besides YV12, the size of the buffer is determined by multiplying the preview image width, height, and bytes per pixel. The width and height can be read from {@link Camera.Parameters#getPreviewSize()}. Bytes per pixel can be computed from {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, using the image format from {@link Camera.Parameters#getPreviewFormat()}.

If using the {@link android.graphics.ImageFormat#YV12} format, the size can be calculated using the equations listed in {@link Camera.Parameters#setPreviewFormat}.

This method is only necessary when {@link #setPreviewCallbackWithBuffer(PreviewCallback)} is used. When {@link #setPreviewCallback(PreviewCallback)} or {@link #setOneShotPreviewCallback(PreviewCallback)} are used, buffers are automatically allocated. When a supplied buffer is too small to hold the preview frame data, preview callback will return null and the buffer will be removed from the buffer queue.

param
callbackBuffer the buffer to add to the queue. The size of the buffer must match the values described above.
see
#setPreviewCallbackWithBuffer(PreviewCallback)

        _addCallbackBuffer(callbackBuffer, CAMERA_MSG_PREVIEW_FRAME);
    
private final voidaddCallbackBuffer(byte[] callbackBuffer, int msgType)

        // CAMERA_MSG_VIDEO_FRAME may be allowed in the future.
        if (msgType != CAMERA_MSG_PREVIEW_FRAME &&
            msgType != CAMERA_MSG_RAW_IMAGE) {
            throw new IllegalArgumentException(
                            "Unsupported message type: " + msgType);
        }

        _addCallbackBuffer(callbackBuffer, msgType);
    
public final voidaddRawImageCallbackBuffer(byte[] callbackBuffer)
Adds a pre-allocated buffer to the raw image callback buffer queue. Applications can add one or more buffers to the queue. When a raw image frame arrives and there is still at least one available buffer, the buffer will be used to hold the raw image data and removed from the queue. Then raw image callback is invoked with the buffer. If a raw image frame arrives but there is no buffer left, the frame is discarded. Applications should add buffers back when they finish processing the data in them by calling this method again in order to avoid running out of raw image callback buffers.

The size of the buffer is determined by multiplying the raw image width, height, and bytes per pixel. The width and height can be read from {@link Camera.Parameters#getPictureSize()}. Bytes per pixel can be computed from {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, using the image format from {@link Camera.Parameters#getPreviewFormat()}.

This method is only necessary when the PictureCallbck for raw image is used while calling {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}.

Please note that by calling this method, the mode for application-managed callback buffers is triggered. If this method has never been called, null will be returned by the raw image callback since there is no image callback buffer available. Furthermore, When a supplied buffer is too small to hold the raw image data, raw image callback will return null and the buffer will be removed from the buffer queue.

param
callbackBuffer the buffer to add to the raw image callback buffer queue. The size should be width * height * (bits per pixel) / 8. An null callbackBuffer will be ignored and won't be added to the queue.
see
#takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. {@hide}

        addCallbackBuffer(callbackBuffer, CAMERA_MSG_RAW_IMAGE);
    
public final voidautoFocus(android.hardware.Camera$AutoFocusCallback cb)
Starts camera auto-focus and registers a callback function to run when the camera is focused. This method is only valid when preview is active (between {@link #startPreview()} and before {@link #stopPreview()}).

Callers should check {@link android.hardware.Camera.Parameters#getFocusMode()} to determine if this method should be called. If the camera does not support auto-focus, it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean, Camera)} callback will be called immediately.

If your application should not be installed on devices without auto-focus, you must declare that your application uses auto-focus with the <uses-feature> manifest element.

If the current flash mode is not {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be fired during auto-focus, depending on the driver and camera hardware.

Auto-exposure lock {@link android.hardware.Camera.Parameters#getAutoExposureLock()} and auto-white balance locks {@link android.hardware.Camera.Parameters#getAutoWhiteBalanceLock()} do not change during and after autofocus. But auto-focus routine may stop auto-exposure and auto-white balance transiently during focusing.

Stopping preview with {@link #stopPreview()}, or triggering still image capture with {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback)}, will not change the the focus position. Applications must call cancelAutoFocus to reset the focus.

If autofocus is successful, consider using {@link android.media.MediaActionSound} to properly play back an autofocus success sound to the user.

param
cb the callback to run
see
#cancelAutoFocus()
see
android.hardware.Camera.Parameters#setAutoExposureLock(boolean)
see
android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)
see
android.media.MediaActionSound

        synchronized (mAutoFocusCallbackLock) {
            mAutoFocusCallback = cb;
        }
        native_autoFocus();
    
private intcameraInitNormal(int cameraId)

        return cameraInitVersion(cameraId, CAMERA_HAL_API_VERSION_NORMAL_CONNECT);
    
public intcameraInitUnspecified(int cameraId)
Connect to the camera service using #connectLegacy

This acts the same as normal except that it will return the detailed error code if open fails instead of converting everything into {@code NO_INIT}.

Intended to use by the camera2 shim only, do not use this for other code.

return
a detailed errno error code, or {@code NO_ERROR} on success
hide

        return cameraInitVersion(cameraId, CAMERA_HAL_API_VERSION_UNSPECIFIED);
    
private intcameraInitVersion(int cameraId, int halVersion)

        mShutterCallback = null;
        mRawImageCallback = null;
        mJpegCallback = null;
        mPreviewCallback = null;
        mPostviewCallback = null;
        mUsingPreviewAllocation = false;
        mZoomListener = null;

        Looper looper;
        if ((looper = Looper.myLooper()) != null) {
            mEventHandler = new EventHandler(this, looper);
        } else if ((looper = Looper.getMainLooper()) != null) {
            mEventHandler = new EventHandler(this, looper);
        } else {
            mEventHandler = null;
        }

        String packageName = ActivityThread.currentPackageName();

        return native_setup(new WeakReference<Camera>(this), cameraId, halVersion, packageName);
    
public final voidcancelAutoFocus()
Cancels any auto-focus function in progress. Whether or not auto-focus is currently in progress, this function will return the focus position to the default. If the camera does not support auto-focus, this is a no-op.

see
#autoFocus(Camera.AutoFocusCallback)

        synchronized (mAutoFocusCallbackLock) {
            mAutoFocusCallback = null;
        }
        native_cancelAutoFocus();
        // CAMERA_MSG_FOCUS should be removed here because the following
        // scenario can happen:
        // - An application uses the same thread for autoFocus, cancelAutoFocus
        //   and looper thread.
        // - The application calls autoFocus.
        // - HAL sends CAMERA_MSG_FOCUS, which enters the looper message queue.
        //   Before event handler's handleMessage() is invoked, the application
        //   calls cancelAutoFocus and autoFocus.
        // - The application gets the old CAMERA_MSG_FOCUS and thinks autofocus
        //   has been completed. But in fact it is not.
        //
        // As documented in the beginning of the file, apps should not use
        // multiple threads to call autoFocus and cancelAutoFocus at the same
        // time. It is HAL's responsibility not to send a CAMERA_MSG_FOCUS
        // message after native_cancelAutoFocus is called.
        mEventHandler.removeMessages(CAMERA_MSG_FOCUS);
    
public static booleancheckInitErrors(int err)

hide

        return err != NO_ERROR;
    
public final android.renderscript.AllocationcreatePreviewAllocation(android.renderscript.RenderScript rs, int usage)

Create a {@link android.renderscript RenderScript} {@link android.renderscript.Allocation Allocation} to use as a destination of preview callback frames. Use {@link #setPreviewCallbackAllocation setPreviewCallbackAllocation} to use the created Allocation as a destination for camera preview frames.

The Allocation will be created with a YUV type, and its contents must be accessed within Renderscript with the {@code rsGetElementAtYuv_*} accessor methods. Its size will be based on the current {@link Parameters#getPreviewSize preview size} configured for this camera.

param
rs the RenderScript context for this Allocation.
param
usage additional usage flags to set for the Allocation. The usage flag {@link android.renderscript.Allocation#USAGE_IO_INPUT} will always be set on the created Allocation, but additional flags may be provided here.
return
a new YUV-type Allocation with dimensions equal to the current preview size.
throws
RSIllegalArgumentException if the usage flags are not compatible with an YUV Allocation.
see
#setPreviewCallbackAllocation
hide

        Parameters p = getParameters();
        Size previewSize = p.getPreviewSize();
        Type.Builder yuvBuilder = new Type.Builder(rs,
                Element.createPixel(rs,
                        Element.DataType.UNSIGNED_8,
                        Element.DataKind.PIXEL_YUV));
        // Use YV12 for wide compatibility. Changing this requires also
        // adjusting camera service's format selection.
        yuvBuilder.setYuvFormat(ImageFormat.YV12);
        yuvBuilder.setX(previewSize.width);
        yuvBuilder.setY(previewSize.height);

        Allocation a = Allocation.createTyped(rs, yuvBuilder.create(),
                usage | Allocation.USAGE_IO_INPUT);

        return a;
    
public final booleandisableShutterSound()
Disable the shutter sound unconditionally.

This is only guaranteed to work for legacy cameras (i.e. initialized with {@link #cameraInitUnspecified}). Trying to call this on a regular camera will force a conditional check in the camera service.

return
{@code true} if the shutter sound state was successfully changed. {@code false} if the shutter sound state could not be changed. {@code true} is also returned if shutter sound playback is already set to the requested state.
hide

        return _enableShutterSound(/*enabled*/false);
    
private native voidenableFocusMoveCallback(int enable)

public final booleanenableShutterSound(boolean enabled)

Enable or disable the default shutter sound when taking a picture.

By default, the camera plays the system-defined camera shutter sound when {@link #takePicture} is called. Using this method, the shutter sound can be disabled. It is strongly recommended that an alternative shutter sound is played in the {@link ShutterCallback} when the system shutter sound is disabled.

Note that devices may not always allow disabling the camera shutter sound. If the shutter sound state cannot be set to the desired value, this method will return false. {@link CameraInfo#canDisableShutterSound} can be used to determine whether the device will allow the shutter sound to be disabled.

param
enabled whether the camera should play the system shutter sound when {@link #takePicture takePicture} is called.
return
{@code true} if the shutter sound state was successfully changed. {@code false} if the shutter sound state could not be changed. {@code true} is also returned if shutter sound playback is already set to the requested state.
see
#takePicture
see
CameraInfo#canDisableShutterSound
see
ShutterCallback

        if (!enabled) {
            IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
            IAudioService audioService = IAudioService.Stub.asInterface(b);
            try {
                if (audioService.isCameraSoundForced()) return false;
            } catch (RemoteException e) {
                Log.e(TAG, "Audio service is unavailable for queries");
            }
        }
        return _enableShutterSound(enabled);
    
protected voidfinalize()

        release();
    
public static voidgetCameraInfo(int cameraId, android.hardware.Camera$CameraInfo cameraInfo)
Returns the information about a particular camera. If {@link #getNumberOfCameras()} returns N, the valid id is 0 to N-1.


                   
        

                            
           
        _getCameraInfo(cameraId, cameraInfo);
        IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
        IAudioService audioService = IAudioService.Stub.asInterface(b);
        try {
            if (audioService.isCameraSoundForced()) {
                // Only set this when sound is forced; otherwise let native code
                // decide.
                cameraInfo.canDisableShutterSound = false;
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Audio service is unavailable for queries");
        }
    
public static android.hardware.Camera$ParametersgetEmptyParameters()
Returns an empty {@link Parameters} for testing purpose.

return
a Parameter object.
hide

        Camera camera = new Camera();
        return camera.new Parameters();
    
public static native intgetNumberOfCameras()
Returns the number of physical cameras available on this device.

public android.hardware.Camera$ParametersgetParameters()
Returns the current settings for this Camera service. If modifications are made to the returned Parameters, they must be passed to {@link #setParameters(Camera.Parameters)} to take effect.

see
#setParameters(Camera.Parameters)

        Parameters p = new Parameters();
        String s = native_getParameters();
        p.unflatten(s);
        return p;
    
public static android.hardware.Camera$ParametersgetParametersCopy(android.hardware.Camera$Parameters parameters)
Returns a copied {@link Parameters}; for shim use only.

param
parameters a non-{@code null} parameters
return
a Parameter object, with all the parameters copied from {@code parameters}.
throws
NullPointerException if {@code parameters} was {@code null}
hide

        if (parameters == null) {
            throw new NullPointerException("parameters must not be null");
        }

        Camera camera = parameters.getOuter();
        Parameters p = camera.new Parameters();
        p.copyFrom(parameters);

        return p;
    
public final native voidlock()
Re-locks the camera to prevent other processes from accessing it. Camera objects are locked by default unless {@link #unlock()} is called. Normally {@link #reconnect()} is used instead.

Since API level 14, camera is automatically locked for applications in {@link android.media.MediaRecorder#start()}. Applications can use the camera (ex: zoom) after recording starts. There is no need to call this after recording starts or stops.

If you are not recording video, you probably do not need this method.

throws
RuntimeException if the camera cannot be re-locked (for example, if the camera is still in use by another process).

private final native voidnative_autoFocus()

private final native voidnative_cancelAutoFocus()

private final native java.lang.Stringnative_getParameters()

private final native voidnative_release()

private final native voidnative_setParameters(java.lang.String params)

private final native intnative_setup(java.lang.Object camera_this, int cameraId, int halVersion, java.lang.String packageName)

private final native voidnative_takePicture(int msgType)

public static android.hardware.Cameraopen(int cameraId)
Creates a new Camera object to access a particular hardware camera. If the same camera is opened by other applications, this will throw a RuntimeException.

You must call {@link #release()} when you are done using the camera, otherwise it will remain locked and be unavailable to other applications.

Your application should only have one Camera object active at a time for a particular hardware camera.

Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.

Caution: On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly using {@link android.os.AsyncTask}) to avoid blocking the main application UI thread.

param
cameraId the hardware camera to access, between 0 and {@link #getNumberOfCameras()}-1.
return
a new Camera object, connected, locked and ready for use.
throws
RuntimeException if opening the camera fails (for example, if the camera is in use by another process or device policy manager has disabled the camera).
see
android.app.admin.DevicePolicyManager#getCameraDisabled(android.content.ComponentName)

    

                                                                                                                                                                                                                              
         
        return new Camera(cameraId);
    
public static android.hardware.Cameraopen()
Creates a new Camera object to access the first back-facing camera on the device. If the device does not have a back-facing camera, this returns null.

see
#open(int)

        int numberOfCameras = getNumberOfCameras();
        CameraInfo cameraInfo = new CameraInfo();
        for (int i = 0; i < numberOfCameras; i++) {
            getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                return new Camera(i);
            }
        }
        return null;
    
public static android.hardware.CameraopenLegacy(int cameraId, int halVersion)
Creates a new Camera object to access a particular hardware camera with given hal API version. If the same camera is opened by other applications or the hal API version is not supported by this device, this will throw a RuntimeException.

You must call {@link #release()} when you are done using the camera, otherwise it will remain locked and be unavailable to other applications.

Your application should only have one Camera object active at a time for a particular hardware camera.

Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.

Caution: On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly using {@link android.os.AsyncTask}) to avoid blocking the main application UI thread.

param
cameraId The hardware camera to access, between 0 and {@link #getNumberOfCameras()}-1.
param
halVersion The HAL API version this camera device to be opened as.
return
a new Camera object, connected, locked and ready for use.
throws
IllegalArgumentException if the {@code halVersion} is invalid
throws
RuntimeException if opening the camera fails (for example, if the camera is in use by another process or device policy manager has disabled the camera).
see
android.app.admin.DevicePolicyManager#getCameraDisabled(android.content.ComponentName)
see
#CAMERA_HAL_API_VERSION_1_0
hide

        if (halVersion < CAMERA_HAL_API_VERSION_1_0) {
            throw new IllegalArgumentException("Invalid HAL version " + halVersion);
        }

        return new Camera(cameraId, halVersion);
    
public static android.hardware.CameraopenUninitialized()

hide

        return new Camera();
    
private static voidpostEventFromNative(java.lang.Object camera_ref, int what, int arg1, int arg2, java.lang.Object obj)

        Camera c = (Camera)((WeakReference)camera_ref).get();
        if (c == null)
            return;

        if (c.mEventHandler != null) {
            Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj);
            c.mEventHandler.sendMessage(m);
        }
    
public final native booleanpreviewEnabled()
Return current preview state. FIXME: Unhide before release

hide

public final native voidreconnect()
Reconnects to the camera service after another process used it. After {@link #unlock()} is called, another process may use the camera; when the process is done, you must reconnect to the camera, which will re-acquire the lock and allow you to continue using the camera.

Since API level 14, camera is automatically locked for applications in {@link android.media.MediaRecorder#start()}. Applications can use the camera (ex: zoom) after recording starts. There is no need to call this after recording starts or stops.

If you are not recording video, you probably do not need this method.

throws
IOException if a connection cannot be re-established (for example, if the camera is still in use by another process).

public final voidrelease()
Disconnects and releases the Camera object resources.

You must call this as soon as you're done with the Camera object.

        native_release();
        mFaceDetectionRunning = false;
    
public voidsetAutoFocusMoveCallback(android.hardware.Camera$AutoFocusMoveCallback cb)
Sets camera auto-focus move callback.

param
cb the callback to run

        mAutoFocusMoveCallback = cb;
        enableFocusMoveCallback((mAutoFocusMoveCallback != null) ? 1 : 0);
    
public final native voidsetDisplayOrientation(int degrees)
Set the clockwise rotation of preview display in degrees. This affects the preview frames and the picture displayed after snapshot. This method is useful for portrait mode applications. Note that preview display of front-facing cameras is flipped horizontally before the rotation, that is, the image is reflected along the central vertical axis of the camera sensor. So the users can see themselves as looking into a mirror.

This does not affect the order of byte array passed in {@link PreviewCallback#onPreviewFrame}, JPEG pictures, or recorded videos. This method is not allowed to be called during preview.

If you want to make the camera image show in the same orientation as the display, you can use the following code.

public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}

int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}

Starting from API level 14, this method can be called when preview is active.

param
degrees the angle that the picture will be rotated clockwise. Valid values are 0, 90, 180, and 270. The starting position is 0 (landscape).
see
#setPreviewDisplay(SurfaceHolder)

public final voidsetErrorCallback(android.hardware.Camera$ErrorCallback cb)
Registers a callback to be invoked when an error occurs.

param
cb The callback to run


                                         
    
      
    
                                        
            
    

                         
        
    
        mErrorCallback = cb;
    
public final voidsetFaceDetectionListener(android.hardware.Camera$FaceDetectionListener listener)
Registers a listener to be notified about the faces detected in the preview frame.

param
listener the listener to notify
see
#startFaceDetection()

        mFaceListener = listener;
    
private final native voidsetHasPreviewCallback(boolean installed, boolean manualBuffer)

public final voidsetOneShotPreviewCallback(android.hardware.Camera$PreviewCallback cb)

Installs a callback to be invoked for the next preview frame in addition to displaying it on the screen. After one invocation, the callback is cleared. This method can be called any time, even when preview is live. Any other preview callbacks are overridden.

If you are using the preview data to create video or still images, strongly consider using {@link android.media.MediaActionSound} to properly indicate image capture or recording start/stop to the user.

param
cb a callback object that receives a copy of the next preview frame, or null to stop receiving callbacks.
see
android.media.MediaActionSound

        mPreviewCallback = cb;
        mOneShot = true;
        mWithBuffer = false;
        if (cb != null) {
            mUsingPreviewAllocation = false;
        }
        setHasPreviewCallback(cb != null, false);
    
public voidsetParameters(android.hardware.Camera$Parameters params)
Changes the settings for this Camera service.

param
params the Parameters to use for this Camera service
throws
RuntimeException if any parameter is invalid or not supported.
see
#getParameters()

        // If using preview allocations, don't allow preview size changes
        if (mUsingPreviewAllocation) {
            Size newPreviewSize = params.getPreviewSize();
            Size currentPreviewSize = getParameters().getPreviewSize();
            if (newPreviewSize.width != currentPreviewSize.width ||
                    newPreviewSize.height != currentPreviewSize.height) {
                throw new IllegalStateException("Cannot change preview size" +
                        " while a preview allocation is configured.");
            }
        }

        native_setParameters(params.flatten());
    
public final voidsetPreviewCallback(android.hardware.Camera$PreviewCallback cb)

Installs a callback to be invoked for every preview frame in addition to displaying them on the screen. The callback will be repeatedly called for as long as preview is active. This method can be called at any time, even while preview is live. Any other preview callbacks are overridden.

If you are using the preview data to create video or still images, strongly consider using {@link android.media.MediaActionSound} to properly indicate image capture or recording start/stop to the user.

param
cb a callback object that receives a copy of each preview frame, or null to stop receiving callbacks.
see
android.media.MediaActionSound

        mPreviewCallback = cb;
        mOneShot = false;
        mWithBuffer = false;
        if (cb != null) {
            mUsingPreviewAllocation = false;
        }
        // Always use one-shot mode. We fake camera preview mode by
        // doing one-shot preview continuously.
        setHasPreviewCallback(cb != null, false);
    
public final voidsetPreviewCallbackAllocation(android.renderscript.Allocation previewAllocation)

Set an {@link android.renderscript.Allocation Allocation} as the target of preview callback data. Use this method for efficient processing of camera preview data with RenderScript. The Allocation must be created with the {@link #createPreviewAllocation createPreviewAllocation } method.

Setting a preview allocation will disable any active preview callbacks set by {@link #setPreviewCallback setPreviewCallback} or {@link #setPreviewCallbackWithBuffer setPreviewCallbackWithBuffer}, and vice versa. Using a preview allocation still requires an active standard preview target to be set, either with {@link #setPreviewTexture setPreviewTexture} or {@link #setPreviewDisplay setPreviewDisplay}.

To be notified when new frames are available to the Allocation, use {@link android.renderscript.Allocation#setIoInputNotificationHandler Allocation.setIoInputNotificationHandler}. To update the frame currently accessible from the Allocation to the latest preview frame, call {@link android.renderscript.Allocation#ioReceive Allocation.ioReceive}.

To disable preview into the Allocation, call this method with a {@code null} parameter.

Once a preview allocation is set, the preview size set by {@link Parameters#setPreviewSize setPreviewSize} cannot be changed. If you wish to change the preview size, first remove the preview allocation by calling {@code setPreviewCallbackAllocation(null)}, then change the preview size, create a new preview Allocation with {@link #createPreviewAllocation createPreviewAllocation}, and set it as the new preview callback allocation target.

If you are using the preview data to create video or still images, strongly consider using {@link android.media.MediaActionSound} to properly indicate image capture or recording start/stop to the user.

param
previewAllocation the allocation to use as destination for preview
throws
IOException if configuring the camera to use the Allocation for preview fails.
throws
IllegalArgumentException if the Allocation's dimensions or other parameters don't meet the requirements.
see
#createPreviewAllocation
see
#setPreviewCallback
see
#setPreviewCallbackWithBuffer
hide

        Surface previewSurface = null;
        if (previewAllocation != null) {
             Parameters p = getParameters();
             Size previewSize = p.getPreviewSize();
             if (previewSize.width != previewAllocation.getType().getX() ||
                     previewSize.height != previewAllocation.getType().getY()) {
                 throw new IllegalArgumentException(
                     "Allocation dimensions don't match preview dimensions: " +
                     "Allocation is " +
                     previewAllocation.getType().getX() +
                     ", " +
                     previewAllocation.getType().getY() +
                     ". Preview is " + previewSize.width + ", " +
                     previewSize.height);
             }
             if ((previewAllocation.getUsage() &
                             Allocation.USAGE_IO_INPUT) == 0) {
                 throw new IllegalArgumentException(
                     "Allocation usage does not include USAGE_IO_INPUT");
             }
             if (previewAllocation.getType().getElement().getDataKind() !=
                     Element.DataKind.PIXEL_YUV) {
                 throw new IllegalArgumentException(
                     "Allocation is not of a YUV type");
             }
             previewSurface = previewAllocation.getSurface();
             mUsingPreviewAllocation = true;
         } else {
             mUsingPreviewAllocation = false;
         }
         setPreviewCallbackSurface(previewSurface);
    
private final native voidsetPreviewCallbackSurface(android.view.Surface s)

public final voidsetPreviewCallbackWithBuffer(android.hardware.Camera$PreviewCallback cb)

Installs a callback to be invoked for every preview frame, using buffers supplied with {@link #addCallbackBuffer(byte[])}, in addition to displaying them on the screen. The callback will be repeatedly called for as long as preview is active and buffers are available. Any other preview callbacks are overridden.

The purpose of this method is to improve preview efficiency and frame rate by allowing preview frame memory reuse. You must call {@link #addCallbackBuffer(byte[])} at some point -- before or after calling this method -- or no callbacks will received.

The buffer queue will be cleared if this method is called with a null callback, {@link #setPreviewCallback(Camera.PreviewCallback)} is called, or {@link #setOneShotPreviewCallback(Camera.PreviewCallback)} is called.

If you are using the preview data to create video or still images, strongly consider using {@link android.media.MediaActionSound} to properly indicate image capture or recording start/stop to the user.

param
cb a callback object that receives a copy of the preview frame, or null to stop receiving callbacks and clear the buffer queue.
see
#addCallbackBuffer(byte[])
see
android.media.MediaActionSound

        mPreviewCallback = cb;
        mOneShot = false;
        mWithBuffer = true;
        if (cb != null) {
            mUsingPreviewAllocation = false;
        }
        setHasPreviewCallback(cb != null, true);
    
public final voidsetPreviewDisplay(android.view.SurfaceHolder holder)
Sets the {@link Surface} to be used for live preview. Either a surface or surface texture is necessary for preview, and preview is necessary to take pictures. The same surface can be re-set without harm. Setting a preview surface will un-set any preview surface texture that was set via {@link #setPreviewTexture}.

The {@link SurfaceHolder} must already contain a surface when this method is called. If you are using {@link android.view.SurfaceView}, you will need to register a {@link SurfaceHolder.Callback} with {@link SurfaceHolder#addCallback(SurfaceHolder.Callback)} and wait for {@link SurfaceHolder.Callback#surfaceCreated(SurfaceHolder)} before calling setPreviewDisplay() or starting preview.

This method must be called before {@link #startPreview()}. The one exception is that if the preview surface is not set (or set to null) before startPreview() is called, then this method may be called once with a non-null parameter to set the preview surface. (This allows camera setup and surface creation to happen in parallel, saving time.) The preview surface may not otherwise change while preview is running.

param
holder containing the Surface on which to place the preview, or null to remove the preview surface
throws
IOException if the method fails (for example, if the surface is unavailable or unsuitable).

        if (holder != null) {
            setPreviewSurface(holder.getSurface());
        } else {
            setPreviewSurface((Surface)null);
        }
    
public final native voidsetPreviewSurface(android.view.Surface surface)

hide

public final native voidsetPreviewTexture(android.graphics.SurfaceTexture surfaceTexture)
Sets the {@link SurfaceTexture} to be used for live preview. Either a surface or surface texture is necessary for preview, and preview is necessary to take pictures. The same surface texture can be re-set without harm. Setting a preview surface texture will un-set any preview surface that was set via {@link #setPreviewDisplay}.

This method must be called before {@link #startPreview()}. The one exception is that if the preview surface texture is not set (or set to null) before startPreview() is called, then this method may be called once with a non-null parameter to set the preview surface. (This allows camera setup and surface creation to happen in parallel, saving time.) The preview surface texture may not otherwise change while preview is running.

The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a SurfaceTexture set as the preview texture have an unspecified zero point, and cannot be directly compared between different cameras or different instances of the same camera, or across multiple runs of the same program.

If you are using the preview data to create video or still images, strongly consider using {@link android.media.MediaActionSound} to properly indicate image capture or recording start/stop to the user.

see
android.media.MediaActionSound
see
android.graphics.SurfaceTexture
see
android.view.TextureView
param
surfaceTexture the {@link SurfaceTexture} to which the preview images are to be sent or null to remove the current preview surface texture
throws
IOException if the method fails (for example, if the surface texture is unavailable or unsuitable).

public final voidsetZoomChangeListener(android.hardware.Camera$OnZoomChangeListener listener)
Registers a listener to be notified when the zoom value is updated by the camera driver during smooth zoom.

param
listener the listener to notify
see
#startSmoothZoom(int)

        mZoomListener = listener;
    
public final voidstartFaceDetection()
Starts the face detection. This should be called after preview is started. The camera will notify {@link FaceDetectionListener} of the detected faces in the preview frame. The detected faces may be the same as the previous ones. Applications should call {@link #stopFaceDetection} to stop the face detection. This method is supported if {@link Parameters#getMaxNumDetectedFaces()} returns a number larger than 0. If the face detection has started, apps should not call this again.

When the face detection is running, {@link Parameters#setWhiteBalance(String)}, {@link Parameters#setFocusAreas(List)}, and {@link Parameters#setMeteringAreas(List)} have no effect. The camera uses the detected faces to do auto-white balance, auto exposure, and autofocus.

If the apps call {@link #autoFocus(AutoFocusCallback)}, the camera will stop sending face callbacks. The last face callback indicates the areas used to do autofocus. After focus completes, face detection will resume sending face callbacks. If the apps call {@link #cancelAutoFocus()}, the face callbacks will also resume.

After calling {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback)} or {@link #stopPreview()}, and then resuming preview with {@link #startPreview()}, the apps should call this method again to resume face detection.

throws
IllegalArgumentException if the face detection is unsupported.
throws
RuntimeException if the method fails or the face detection is already running.
see
FaceDetectionListener
see
#stopFaceDetection()
see
Parameters#getMaxNumDetectedFaces()

        if (mFaceDetectionRunning) {
            throw new RuntimeException("Face detection is already running");
        }
        _startFaceDetection(CAMERA_FACE_DETECTION_HW);
        mFaceDetectionRunning = true;
    
public final native voidstartPreview()
Starts capturing and drawing preview frames to the screen. Preview will not actually start until a surface is supplied with {@link #setPreviewDisplay(SurfaceHolder)} or {@link #setPreviewTexture(SurfaceTexture)}.

If {@link #setPreviewCallback(Camera.PreviewCallback)}, {@link #setOneShotPreviewCallback(Camera.PreviewCallback)}, or {@link #setPreviewCallbackWithBuffer(Camera.PreviewCallback)} were called, {@link Camera.PreviewCallback#onPreviewFrame(byte[], Camera)} will be called when preview data becomes available.

public final native voidstartSmoothZoom(int value)
Zooms to the requested value smoothly. The driver will notify {@link OnZoomChangeListener} of the zoom value and whether zoom is stopped at the time. For example, suppose the current zoom is 0 and startSmoothZoom is called with value 3. The {@link Camera.OnZoomChangeListener#onZoomChange(int, boolean, Camera)} method will be called three times with zoom values 1, 2, and 3. Applications can call {@link #stopSmoothZoom} to stop the zoom earlier. Applications should not call startSmoothZoom again or change the zoom value before zoom stops. If the supplied zoom value equals to the current zoom value, no zoom callback will be generated. This method is supported if {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} returns true.

param
value zoom value. The valid range is 0 to {@link android.hardware.Camera.Parameters#getMaxZoom}.
throws
IllegalArgumentException if the zoom value is invalid.
throws
RuntimeException if the method fails.
see
#setZoomChangeListener(OnZoomChangeListener)

public final voidstopFaceDetection()
Stops the face detection.

see
#startFaceDetection()

        _stopFaceDetection();
        mFaceDetectionRunning = false;
    
public final voidstopPreview()
Stops capturing and drawing preview frames to the surface, and resets the camera for a future call to {@link #startPreview()}.

        _stopPreview();
        mFaceDetectionRunning = false;

        mShutterCallback = null;
        mRawImageCallback = null;
        mPostviewCallback = null;
        mJpegCallback = null;
        synchronized (mAutoFocusCallbackLock) {
            mAutoFocusCallback = null;
        }
        mAutoFocusMoveCallback = null;
    
public final native voidstopSmoothZoom()
Stops the smooth zoom. Applications should wait for the {@link OnZoomChangeListener} to know when the zoom is actually stopped. This method is supported if {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} is true.

throws
RuntimeException if the method fails.

public final voidtakePicture(android.hardware.Camera$ShutterCallback shutter, android.hardware.Camera$PictureCallback raw, android.hardware.Camera$PictureCallback jpeg)
Equivalent to takePicture(shutter, raw, null, jpeg).

see
#takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback)

        takePicture(shutter, raw, null, jpeg);
    
public final voidtakePicture(android.hardware.Camera$ShutterCallback shutter, android.hardware.Camera$PictureCallback raw, android.hardware.Camera$PictureCallback postview, android.hardware.Camera$PictureCallback jpeg)
Triggers an asynchronous image capture. The camera service will initiate a series of callbacks to the application as the image capture progresses. The shutter callback occurs after the image is captured. This can be used to trigger a sound to let the user know that image has been captured. The raw callback occurs when the raw image data is available (NOTE: the data will be null if there is no raw image callback buffer available or the raw image callback buffer is not large enough to hold the raw image). The postview callback occurs when a scaled, fully processed postview image is available (NOTE: not all hardware supports this). The jpeg callback occurs when the compressed image is available. If the application does not need a particular callback, a null can be passed instead of a callback method.

This method is only valid when preview is active (after {@link #startPreview()}). Preview will be stopped after the image is taken; callers must call {@link #startPreview()} again if they want to re-start preview or take more pictures. This should not be called between {@link android.media.MediaRecorder#start()} and {@link android.media.MediaRecorder#stop()}.

After calling this method, you must not call {@link #startPreview()} or take another picture until the JPEG callback has returned.

param
shutter the callback for image capture moment, or null
param
raw the callback for raw (uncompressed) image data, or null
param
postview callback with postview image data, may be null
param
jpeg the callback for JPEG image data, or null

        mShutterCallback = shutter;
        mRawImageCallback = raw;
        mPostviewCallback = postview;
        mJpegCallback = jpeg;

        // If callback is not set, do not send me callbacks.
        int msgType = 0;
        if (mShutterCallback != null) {
            msgType |= CAMERA_MSG_SHUTTER;
        }
        if (mRawImageCallback != null) {
            msgType |= CAMERA_MSG_RAW_IMAGE;
        }
        if (mPostviewCallback != null) {
            msgType |= CAMERA_MSG_POSTVIEW_FRAME;
        }
        if (mJpegCallback != null) {
            msgType |= CAMERA_MSG_COMPRESSED_IMAGE;
        }

        native_takePicture(msgType);
        mFaceDetectionRunning = false;
    
public final native voidunlock()
Unlocks the camera to allow another process to access it. Normally, the camera is locked to the process with an active Camera object until {@link #release()} is called. To allow rapid handoff between processes, you can call this method to release the camera temporarily for another process to use; once the other process is done you can call {@link #reconnect()} to reclaim the camera.

This must be done before calling {@link android.media.MediaRecorder#setCamera(Camera)}. This cannot be called after recording starts.

If you are not recording video, you probably do not need this method.

throws
RuntimeException if the camera cannot be unlocked.