public static 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.


Public methods

abstract void onSurfaceRequested(SurfaceRequest request)

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

Public methods


public abstract void onSurfaceRequested (SurfaceRequest request)

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 SurfaceRequest.provideSurface(Surface, Executor, Consumer) will be invoked with a SurfaceRequest.Result containing SurfaceRequest.Result.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;

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

         // 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.

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