IT. Expert System.

Android Reference

Camera


android.hardware

Class 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 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 open(int).
    2. Get existing (default) settings with getParameters().
    3. If necessary, modify the returned Camera.Parameters object and call setParameters(Camera.Parameters).
    4. If desired, call setDisplayOrientation(int).
    5. Important: Pass a fully initialized SurfaceHolder to setPreviewDisplay(SurfaceHolder). Without a surface, the camera will be unable to start the preview.
    6. Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture.
    7. When you want, call 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 startPreview() again first.
    9. Call stopPreview() to stop updating the preview surface.
    10. Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in Activity.onPause() (and re-open() it in 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 unlock() to allow the media process to access the camera.
    3. Pass the camera to MediaRecorder.setCamera(Camera). See MediaRecorder information about video recording.
    4. When finished recording, call reconnect() to re-acquire and re-lock the camera.
    5. If desired, restart preview and take more photos or videos.
    6. Call stopPreview() and 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 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.

    • Field Detail

      • ACTION_NEW_PICTURE

        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. Intent.getData() is URI of the picture.
        See Also:
        Constant Field Values
      • ACTION_NEW_VIDEO

        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. Intent.getData() is URI of the video.
        See Also:
        Constant Field Values
      • CAMERA_ERROR_SERVER_DIED

        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.
        See Also:
        Camera.ErrorCallback, Constant Field Values
    • Method Detail

      • getNumberOfCameras

        public static int getNumberOfCameras()
        Returns the number of physical cameras available on this device.
      • getCameraInfo

        public static void getCameraInfo(int cameraId,
                         Camera.CameraInfo cameraInfo)
        Returns the information about a particular camera. If getNumberOfCameras() returns N, the valid id is 0 to N-1.
      • open

        public static 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 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 AsyncTask) to avoid blocking the main application UI thread.

        Parameters:
        cameraId - the hardware camera to access, between 0 and getNumberOfCameras()-1.
        Returns:
        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 Also:
        DevicePolicyManager.getCameraDisabled(android.content.ComponentName)
      • open

        public static 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.
        See Also:
        open(int)
      • finalize

        protected void finalize()
        Description copied from class: Object
        Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

        Note that objects that override finalize are significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicit close method (and implement Closeable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like a BigInteger where typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

        If you must use finalizers, consider at least providing your own ReferenceQueue and having your own thread process that queue.

        Unlike constructors, finalizers are not automatically chained. You are responsible for calling super.finalize() yourself.

        Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.

        Overrides:
        finalize in class Object
      • release

        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.

      • unlock

        public final 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 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 reconnect() to reclaim the camera.

        This must be done before calling 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.
      • lock

        public final void lock()
        Re-locks the camera to prevent other processes from accessing it. Camera objects are locked by default unless unlock() is called. Normally reconnect() is used instead.

        Since API level 14, camera is automatically locked for applications in 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).
      • reconnect

        public final void reconnect()
                             throws IOException
        Reconnects to the camera service after another process used it. After 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 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).
      • setPreviewDisplay

        public final void setPreviewDisplay(SurfaceHolder holder)
                                     throws IOException
        Sets the 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 setPreviewTexture(android.graphics.SurfaceTexture).

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

        This method must be called before 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.

        Parameters:
        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).
      • setPreviewTexture

        public final void setPreviewTexture(SurfaceTexture surfaceTexture)
                                     throws IOException
        Sets the 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 setPreviewDisplay(android.view.SurfaceHolder).

        This method must be called before 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 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 MediaActionSound to properly indicate image capture or recording start/stop to the user.

        Parameters:
        surfaceTexture - the 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).
        See Also:
        MediaActionSound, SurfaceTexture, TextureView
      • stopPreview

        public final void stopPreview()
        Stops capturing and drawing preview frames to the surface, and resets the camera for a future call to startPreview().
      • previewEnabled

        public final boolean previewEnabled()
        Return current preview state. FIXME: Unhide before release
      • setPreviewCallback

        public final void setPreviewCallback(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 MediaActionSound to properly indicate image capture or recording start/stop to the user.

        Parameters:
        cb - a callback object that receives a copy of each preview frame, or null to stop receiving callbacks.
        See Also:
        MediaActionSound
      • setOneShotPreviewCallback

        public final void setOneShotPreviewCallback(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 MediaActionSound to properly indicate image capture or recording start/stop to the user.

        Parameters:
        cb - a callback object that receives a copy of the next preview frame, or null to stop receiving callbacks.
        See Also:
        MediaActionSound
      • setPreviewCallbackWithBuffer

        public final void setPreviewCallbackWithBuffer(Camera.PreviewCallback cb)

        Installs a callback to be invoked for every preview frame, using buffers supplied with 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 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, setPreviewCallback(Camera.PreviewCallback) is called, or setOneShotPreviewCallback(Camera.PreviewCallback) is called.

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

        Parameters:
        cb - a callback object that receives a copy of the preview frame, or null to stop receiving callbacks and clear the buffer queue.
        See Also:
        addCallbackBuffer(byte[]), MediaActionSound
      • addRawImageCallbackBuffer

        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 Camera.Parameters.getPictureSize(). Bytes per pixel can be computed from ImageFormat.getBitsPerPixel(int) / 8, using the image format from Camera.Parameters.getPreviewFormat().

        This method is only necessary when the PictureCallbck for raw image is used while calling 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.

        Parameters:
        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 Also:
        {@hide}
      • cancelAutoFocus

        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.
        See Also:
        autoFocus(Camera.AutoFocusCallback)
      • setAutoFocusMoveCallback

        public void setAutoFocusMoveCallback(Camera.AutoFocusMoveCallback cb)
        Sets camera auto-focus move callback.
        Parameters:
        cb - the callback to run
      • takePicture

        public final void takePicture(Camera.ShutterCallback shutter,
                       Camera.PictureCallback raw,
                       Camera.PictureCallback postview,
                       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 startPreview()). Preview will be stopped after the image is taken; callers must call startPreview() again if they want to re-start preview or take more pictures. This should not be called between MediaRecorder.start() and MediaRecorder.stop().

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

        Parameters:
        shutter - the callback for image capture moment, or null
        raw - the callback for raw (uncompressed) image data, or null
        postview - callback with postview image data, may be null
        jpeg - the callback for JPEG image data, or null
      • setDisplayOrientation

        public final 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 Camera.PreviewCallback.onPreviewFrame(byte[], android.hardware.Camera), 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.

        Parameters:
        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 Also:
        setPreviewDisplay(SurfaceHolder)
      • setZoomChangeListener

        public final void setZoomChangeListener(Camera.OnZoomChangeListener listener)
        Registers a listener to be notified when the zoom value is updated by the camera driver during smooth zoom.
        Parameters:
        listener - the listener to notify
        See Also:
        startSmoothZoom(int)
      • setFaceDetectionListener

        public final void setFaceDetectionListener(Camera.FaceDetectionListener listener)
        Registers a listener to be notified about the faces detected in the preview frame.
        Parameters:
        listener - the listener to notify
        See Also:
        startFaceDetection()
      • stopFaceDetection

        public final void stopFaceDetection()
        Stops the face detection.
        See Also:
        startFaceDetection()
      • setErrorCallback

        public final void setErrorCallback(Camera.ErrorCallback cb)
        Registers a callback to be invoked when an error occurs.
        Parameters:
        cb - The callback to run
      • setParameters

        public void setParameters(Camera.Parameters params)
        Changes the settings for this Camera service.
        Parameters:
        params - the Parameters to use for this Camera service
        Throws:
        RuntimeException - if any parameter is invalid or not supported.
        See Also:
        getParameters()


Content

Android Reference

Java basics

Java Enterprise Edition (EE)

Java Standard Edition (SE)

SQL

HTML

PHP

CSS

Java Script

MYSQL

JQUERY

VBS

REGEX

C

C++

C#

Design patterns

RFC (standard status)

RFC (proposed standard status)

RFC (draft standard status)

RFC (informational status)

RFC (experimental status)

RFC (best current practice status)

RFC (historic status)

RFC (unknown status)

IT dictionary

License.
All information of this service is derived from the free sources and is provided solely in the form of quotations. This service provides information and interfaces solely for the familiarization (not ownership) and under the "as is" condition.
Copyright 2016 © ELTASK.COM. All rights reserved.
Site is optimized for mobile devices.
Downloads: 1521 / 96487320. Delta: 0.06521 с