Camerapublic 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:
- Obtain an instance of Camera from {@link #open(int)}.
- Get existing (default) settings with {@link #getParameters()}.
- If necessary, modify the returned {@link Camera.Parameters} object and call
{@link #setParameters(Camera.Parameters)}.
- If desired, call {@link #setDisplayOrientation(int)}.
- Important: Pass a fully initialized {@link SurfaceHolder} to
{@link #setPreviewDisplay(SurfaceHolder)}. Without a surface, the camera
will be unable to start the preview.
- Important: Call {@link #startPreview()} to start updating the
preview surface. Preview must be started before you can take a picture.
- 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.
- After taking a picture, preview display will have stopped. To take more
photos, call {@link #startPreview()} again first.
- Call {@link #stopPreview()} to stop updating the preview surface.
- 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:
- Obtain and initialize a Camera and start preview as described above.
- Call {@link #unlock()} to allow the media process to access the camera.
- Pass the camera to {@link android.media.MediaRecorder#setCamera(Camera)}.
See {@link android.media.MediaRecorder} information about video recording.
- When finished recording, call {@link #reconnect()} to re-acquire
and re-lock the camera.
- If desired, restart preview and take more photos or videos.
- 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.
|
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_PICTUREBroadcast 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_VIDEOBroadcast 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_0Camera HAL device API version 1.0 | private static final int | CAMERA_HAL_API_VERSION_NORMAL_CONNECTA constant meaning the normal camera connect/open will be used. | private static final int | CAMERA_HAL_API_VERSION_UNSPECIFIEDUsed to indicate HAL version un-specified. | private static final int | CAMERA_FACE_DETECTION_HWHardware face detection. It does not use much CPU. | private static final int | CAMERA_FACE_DETECTION_SWSoftware face detection. It uses some CPU. | public static final int | CAMERA_ERROR_UNKNOWNUnspecified camera error. | public static final int | CAMERA_ERROR_SERVER_DIEDMedia 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.
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 void | addCallbackBuffer(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.
_addCallbackBuffer(callbackBuffer, CAMERA_MSG_PREVIEW_FRAME);
| private final void | addCallbackBuffer(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 void | addRawImageCallbackBuffer(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.
addCallbackBuffer(callbackBuffer, CAMERA_MSG_RAW_IMAGE);
| public final void | autoFocus(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.
synchronized (mAutoFocusCallbackLock) {
mAutoFocusCallback = cb;
}
native_autoFocus();
| private int | cameraInitNormal(int cameraId)
return cameraInitVersion(cameraId, CAMERA_HAL_API_VERSION_NORMAL_CONNECT);
| public int | cameraInitUnspecified(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 cameraInitVersion(cameraId, CAMERA_HAL_API_VERSION_UNSPECIFIED);
| private int | cameraInitVersion(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 void | cancelAutoFocus()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.
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 boolean | checkInitErrors(int err)
return err != NO_ERROR;
| public final android.renderscript.Allocation | createPreviewAllocation(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.
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 boolean | disableShutterSound()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 _enableShutterSound(/*enabled*/false);
| private native void | enableFocusMoveCallback(int enable)
| public final boolean | enableShutterSound(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.
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 void | finalize()
release();
| public static void | getCameraInfo(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$Parameters | getEmptyParameters()Returns an empty {@link Parameters} for testing purpose.
Camera camera = new Camera();
return camera.new Parameters();
| public static native int | getNumberOfCameras()Returns the number of physical cameras available on this device.
| public android.hardware.Camera$Parameters | getParameters()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.
Parameters p = new Parameters();
String s = native_getParameters();
p.unflatten(s);
return p;
| public static android.hardware.Camera$Parameters | getParametersCopy(android.hardware.Camera$Parameters parameters)Returns a copied {@link Parameters}; for shim use only.
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 void | lock()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.
| private final native void | native_autoFocus()
| private final native void | native_cancelAutoFocus()
| private final native java.lang.String | native_getParameters()
| private final native void | native_release()
| private final native void | native_setParameters(java.lang.String params)
| private final native int | native_setup(java.lang.Object camera_this, int cameraId, int halVersion, java.lang.String packageName)
| private final native void | native_takePicture(int msgType)
| public static android.hardware.Camera | open(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.
return new Camera(cameraId);
| public static android.hardware.Camera | open()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.
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.Camera | openLegacy(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.
if (halVersion < CAMERA_HAL_API_VERSION_1_0) {
throw new IllegalArgumentException("Invalid HAL version " + halVersion);
}
return new Camera(cameraId, halVersion);
| public static android.hardware.Camera | openUninitialized()
return new Camera();
| private static void | postEventFromNative(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 boolean | previewEnabled()Return current preview state.
FIXME: Unhide before release
| public final native void | reconnect()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.
| public final void | release()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 void | setAutoFocusMoveCallback(android.hardware.Camera$AutoFocusMoveCallback cb)Sets camera auto-focus move callback.
mAutoFocusMoveCallback = cb;
enableFocusMoveCallback((mAutoFocusMoveCallback != null) ? 1 : 0);
| public final native void | setDisplayOrientation(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.
| public final void | setErrorCallback(android.hardware.Camera$ErrorCallback cb)Registers a callback to be invoked when an error occurs.
mErrorCallback = cb;
| public final void | setFaceDetectionListener(android.hardware.Camera$FaceDetectionListener listener)Registers a listener to be notified about the faces detected in the
preview frame.
mFaceListener = listener;
| private final native void | setHasPreviewCallback(boolean installed, boolean manualBuffer)
| public final void | setOneShotPreviewCallback(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.
mPreviewCallback = cb;
mOneShot = true;
mWithBuffer = false;
if (cb != null) {
mUsingPreviewAllocation = false;
}
setHasPreviewCallback(cb != null, false);
| public void | setParameters(android.hardware.Camera$Parameters params)Changes the settings for this Camera service.
// 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 void | setPreviewCallback(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.
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 void | setPreviewCallbackAllocation(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.
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 void | setPreviewCallbackSurface(android.view.Surface s)
| public final void | setPreviewCallbackWithBuffer(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.
mPreviewCallback = cb;
mOneShot = false;
mWithBuffer = true;
if (cb != null) {
mUsingPreviewAllocation = false;
}
setHasPreviewCallback(cb != null, true);
| public final void | setPreviewDisplay(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.
if (holder != null) {
setPreviewSurface(holder.getSurface());
} else {
setPreviewSurface((Surface)null);
}
| public final native void | setPreviewSurface(android.view.Surface surface)
| public final native void | setPreviewTexture(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.
| public final void | setZoomChangeListener(android.hardware.Camera$OnZoomChangeListener listener)Registers a listener to be notified when the zoom value is updated by the
camera driver during smooth zoom.
mZoomListener = listener;
| public final void | startFaceDetection()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.
if (mFaceDetectionRunning) {
throw new RuntimeException("Face detection is already running");
}
_startFaceDetection(CAMERA_FACE_DETECTION_HW);
mFaceDetectionRunning = true;
| public final native void | startPreview()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 void | startSmoothZoom(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.
| public final void | stopFaceDetection()Stops the face detection.
_stopFaceDetection();
mFaceDetectionRunning = false;
| public final void | stopPreview()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 void | stopSmoothZoom()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.
| public final void | takePicture(android.hardware.Camera$ShutterCallback shutter, android.hardware.Camera$PictureCallback raw, android.hardware.Camera$PictureCallback jpeg)Equivalent to takePicture(shutter, raw, null, jpeg).
takePicture(shutter, raw, null, jpeg);
| public final void | takePicture(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.
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 void | unlock()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.
|
|