SoFunction
Updated on 2025-04-10

Detailed explanation of the use of amera2 Preview in Android development

Preface

Camera2 is the new Camera framework for Android. Overall, Camera2 provides many standard interfaces for applications, allowing more functions to be controlled through parameters; however, flexibility also brings architectural complexity. This article discusses the implementation of the Preview function of Camera2, and discusses the minimum set of modules used in Camera2.

1. What modules are needed for Camera2 Preview

To sum up, the following modules were used.

  • SurfaceTexture: SurfaceTextureListener
  • CameraManager
  • CameraDevice StateCallback
  • CameraDevice createCaptureSession
  • 、 CaptureRequest

2. The relationship between the functions and the relationship between each module

The following is a detailed analysis of the functions and relationships between these modules.

2.1 SurfaceTexture: SurfaceTextureListener

2.1.1 First look at the explanation about SurfaceTexture

The main purpose is to receive the camera preview data and display it on the UI.

Captures frames from an image stream as an OpenGL ES texture.
Capture frames from image streams as OpenGL ES textures.

The image stream may come from either camera preview or video decode. A created from a SurfaceTexture can be used as an output destination for the .camera2, , , and APIs. When updateTexImage is called, the contents of the texture object specified when the SurfaceTexture was created are updated to contain the most recent image from the image stream. This may cause some frames of the stream to be skipped.

2.1.2 Use of SurfaceTextureListener

This Listener can be used to get notifications when the surface texture associated with this Surface Texture is available.
When the SurfaceTexture is available notification, the action to initialize camera is performed.
The sample code is as follows,

private final SurfaceTextureListener mSurfaceTextureListener = new SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
            (TAG, "onSurfaceTextureAvailable: ++");
            try {
                (TAG, "onCreate: call initCamera()");
                initCamera();
            } catch (CameraAccessException e) {
                ();
            }
        }
 
        @Override
        public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
            (TAG, "onSurfaceTextureSizeChanged: ++");
        }
 
        @Override
        public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
            (TAG, "onSurfaceTextureDestroyed: ++");
            return false;
        }
 
        @Override
        public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
            (TAG, "onSurfaceTextureUpdated: ++");
        }
    };

2.2 CameraManager

2.2.1 The role of CameraManager

A system service manager for detecting, characterizing, and connecting to CameraDevices.
A system service manager for detecting, characterizing and connecting camera devices.

2.2.2 Open Camera using CameraManager

The sample code is as follows,

Notice:
The first parameter of openCamera is which camera to turn on, 0 represents the rear camera; 1 represents the front camera; 2 represents the external camera. The front camera is turned on here.
The second parameter is the StateCallback of CameraDevice, which is parsed later;
The third parameter is Handler, here we place the Handler in a newly created thread;

CameraManager manager = (CameraManager) (Context.CAMERA_SERVICE);
("1", stateCallback, mBackgroundHander);

2.3 CameraDevice StateCallback

2.3.1 The role of StateCallback

A callback objects for receiving updates about the state of a camera device.
A callback object for receiving updates to the camera device status.

2.3.2 Sample code of StateCallback

We will create a Preview Session in the onOpened() function!

 
             stateCallback = new () {
                @Override
                public void onOpened(@NonNull CameraDevice camera) {
                    (TAG, "onOpened: ++");
                    mCameraDevice = camera;
                    createPreviewSession();
                }
 
                @Override
                public void onDisconnected(@NonNull CameraDevice camera) {
                    (TAG, "onDisconnected: ++");
                }
 
                @Override
                public void onError(@NonNull CameraDevice camera, int error) {
                    (TAG, "onError: ++");
                }
            };

2.4 CameraDevice createCaptureSession

2.4.1 New

A builder for capture requests.

2.4.2 Create a new CameraDevice createCaptureSession

A configured capture session for a CameraDevice, used for capturing images from the camera or reprocessing images captured from the camera in the same session previously.

2.4.3 Creating a CaptureRequest

An immutable package of settings and outputs needed to capture a single image from the camera device.

Contains the configuration for the capture hardware (sensor, lens, flash), the processing pipeline, the control algorithms, and the output buffers. Also contains the list of target Surfaces to send image data to for this capture.

The example code for this part is as follows:

 
    private void createPreviewSession() {
        SurfaceTexture surfaceTexture = ();
        // should be preview size, will got it later
        ((), ());
        mImageReader = ((), (),
                , /*maxImages*/2);
 
        Surface surface =new Surface(surfaceTexture);
 
        try {
            mPreviewRequstBuilder = (CameraDevice.TEMPLATE_PREVIEW);
            (surface);
 
            ((surface, ()),
                    new () {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            (TAG, "onConfigured: ");
                            if (mCameraDevice == null) {
                                return;
                            } else {
                                mCaptureSession = session;
                            }
 
                            mPreviewRequest = ();
                            try {
                                (mPreviewRequest, null, mBackgroundHander);
                            } catch (CameraAccessException e) {
                                ();
                            }
                        }
 
                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                            (TAG, "onConfigureFailed: ");
                        }
                    }, mBackgroundHander);
        } catch (CameraAccessException e) {
            ();
        }
    }

summary

Camera2 uses the SurfaceTexture component to display the Preview video stream;
Use CameraManager to open CameraDevice camera, and at the same time insert the StateCallback of CameraDevice callback function CameraDevice to feedback camera status;
When the Camera status is Opened, it is created as a preview and associates the surface to the builder; then createCaptureSession of the CameraDevice. When receiving the onConfigured message, configure such as sensor, lens, flash, etc., and then call the Builder's build function to complete the configuration of CaptureRequest, and finally set the session to repeat mode.

This is the end of this article about the detailed explanation of the use of amera2 Preview in Android development. For more related content on Android Camera2 Preview, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!