Preview.SurfaceProvider


interface Preview.SurfaceProvider


A interface implemented by the application to provide a Surface for Preview.

This interface is implemented by the application to provide a Surface. This will be called by CameraX when it needs a Surface for Preview. It also signals when the Surface is no longer in use by CameraX.

Summary

Public functions

Unit

Called when a new Surface has been requested by the camera.

Public functions

onSurfaceRequested

Added in 1.0.0
fun onSurfaceRequested(request: SurfaceRequest): Unit

Called when a new Surface has been requested by the camera.

This is called every time a new surface is required to keep the preview running. The camera may repeatedly request surfaces throughout usage of a Preview use case, but only a single request will be active at a time.

A request is considered active until it is fulfilled, marked as 'will not complete', or cancelled by the camera. After one of these conditions occurs, a request is considered completed.

Once a request is successfully completed, it is guaranteed that if a new request is made, the Surface used to fulfill the previous request will be detached from the camera and provideSurface will be invoked with a androidx.camera.core.SurfaceRequest.Result containing RESULT_SURFACE_USED_SUCCESSFULLY. Example:

class MyGlSurfaceProvider implements Preview.SurfaceProvider {
    // This executor must have also been used with Preview.setSurfaceProvider() to
    // ensure onSurfaceRequested() is called on our GL thread.
    Executor mGlExecutor;

    @Override
    public void onSurfaceRequested(@NonNull SurfaceRequest request) {
        // If our GL thread/context is shutting down. Signal we will not fulfill
        // the request.
        if (isShuttingDown()) {
            request.willNotProvideSurface();
            return;
        }

        // Create the surface and attempt to provide it to the camera.
        Surface surface = resetGlInputSurface(request.getResolution());

        // Provide the surface and wait for the result to clean up the surface.
        request.provideSurface(surface, mGlExecutor, (result) -> {
            // In all cases (even errors), we can clean up the state. As an
            // optimization, we could also optionally check for REQUEST_CANCELLED
            // since we may be able to reuse the surface on subsequent surface requests.
            closeGlInputSurface(surface);
        });
    }
}
Parameters
request: SurfaceRequest

the request for a surface which contains the requirements of the surface and methods for completing the request.