ProcessCameraProvider

@RequiresApi(value = 21)
class ProcessCameraProvider : CameraProvider


A singleton which can be used to bind the lifecycle of cameras to any LifecycleOwner within an application's process.

Only a single process camera provider can exist within a process, and it can be retrieved with getInstance.

Heavyweight resources, such as open and running camera devices, will be scoped to the lifecycle provided to bindToLifecycle. Other lightweight resources, such as static camera characteristics, may be retrieved and cached upon first retrieval of this provider with getInstance, and will persist for the lifetime of the process.

This is the standard provider for applications to use.

Summary

Public functions

ConcurrentCamera

Binds list of SingleCameraConfigs to LifecycleOwner.

Camera
@MainThread
bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    useCaseGroup: UseCaseGroup
)

Binds a UseCaseGroup to a LifecycleOwner.

Camera
@MainThread
bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    useCases: Array<UseCase!>
)

Binds the collection of UseCase to a LifecycleOwner.

java-static Unit

Perform one-time configuration of the ProcessCameraProvider singleton with the given CameraXConfig.

(Mutable)List<CameraInfo!>

Returns CameraInfo instances of the available cameras.

(Mutable)List<(Mutable)List<CameraInfo!>!>

Returns list of CameraInfo instances of the available concurrent cameras.

java-static ListenableFuture<ProcessCameraProvider!>
getInstance(context: Context)

Retrieves the ProcessCameraProvider associated with the current process.

Boolean
hasCamera(cameraSelector: CameraSelector)

Checks whether this provider supports at least one camera that meets the requirements from a .

Boolean
isBound(useCase: UseCase)

Returns true if the UseCase is bound to a lifecycle.

Boolean

Returns whether there is a ConcurrentCamera bound.

ListenableFuture<Void!>

Allows shutting down this ProcessCameraProvider instance so a new instance can be retrieved by getInstance.

Unit

Unbinds all specified use cases from the lifecycle.

Unit

Unbinds all use cases from the lifecycle and removes them from CameraX.

Public functions

bindToLifecycle

Added in 1.3.0
@MainThread
fun bindToLifecycle(
    singleCameraConfigs: (Mutable)List<ConcurrentCamera.SingleCameraConfig!>
): ConcurrentCamera

Binds list of SingleCameraConfigs to LifecycleOwner.

The concurrent camera is only supporting two cameras currently. If the input list of SingleCameraConfigs have less or more than two SingleCameraConfigs, IllegalArgumentException will be thrown. If the device is not supporting FEATURE_CAMERA_CONCURRENT or cameras are already used by other UseCases, UnsupportedOperationException will be thrown.

To set up concurrent camera, call getAvailableConcurrentCameraInfos to get the list of available combinations of concurrent cameras. Each sub-list contains the CameraInfos for a combination of cameras that can be operated concurrently. Each camera can have its own UseCases and LifecycleOwner. See CameraX lifecycles

Parameters
singleCameraConfigs: (Mutable)List<ConcurrentCamera.SingleCameraConfig!>

input list of SingleCameraConfigs.

Returns
ConcurrentCamera

output ConcurrentCamera instance.

Throws
java.lang.IllegalArgumentException

If less or more than two camera configs are provided.

java.lang.UnsupportedOperationException

If device is not supporting concurrent camera or cameras are already used by other UseCases.

bindToLifecycle

Added in 1.0.0
@MainThread
fun bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    useCaseGroup: UseCaseGroup
): Camera

Binds a UseCaseGroup to a LifecycleOwner.

Similar to bindToLifecycle, with the addition that the bound collection of UseCase share parameters defined by UseCaseGroup such as consistent camera sensor rect across all UseCases.

If one UseCase is in multiple UseCaseGroups, it will be linked to the UseCaseGroup in the latest bindToLifecycle call.

bindToLifecycle

@MainThread
fun bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    useCases: Array<UseCase!>
): Camera

Binds the collection of UseCase to a LifecycleOwner.

The state of the lifecycle will determine when the cameras are open, started, stopped and closed. When started, the use cases receive camera data.

Binding to a lifecycleOwner in state currently in STARTED or greater will also initialize and start data capture. If the camera was already running this may cause a new initialization to occur temporarily stopping data from the camera before restarting it.

Multiple use cases can be bound via adding them all to a single bindToLifecycle call, or by using multiple bindToLifecycle calls. Using a single call that includes all the use cases helps to set up a camera session correctly for all uses cases, such as by allowing determination of resolutions depending on all the use cases bound being bound. If the use cases are bound separately, it will find the supported resolution with the priority depending on the binding sequence. If the use cases are bound with a single call, it will find the supported resolution with the priority in sequence of ImageCapture, Preview and then ImageAnalysis. The resolutions that can be supported depends on the camera device hardware level that there are some default guaranteed resolutions listed in createCaptureSession.

Currently up to 3 use cases may be bound to a Lifecycle at any time. Exceeding capability of target camera device will throw an IllegalArgumentException.

A UseCase should only be bound to a single lifecycle and camera selector a time. Attempting to bind a use case to a lifecycle when it is already bound to another lifecycle is an error, and the use case binding will not change. Attempting to bind the same use case to multiple camera selectors is also an error and will not change the binding.

If different use cases are bound to different camera selectors that resolve to distinct cameras, but the same lifecycle, only one of the cameras will operate at a time. The non-operating camera will not become active until it is the only camera with use cases bound.

The Camera returned is determined by the given camera selector, plus other internal requirements, possibly from use case configurations. The camera returned from bindToLifecycle may differ from the camera determined solely by a camera selector. If the camera selector can't resolve a valid camera under the requirements, an IllegalArgumentException will be thrown.

Only UseCase bound to latest active Lifecycle can keep alive. UseCase bound to other Lifecycle will be stopped.

Parameters
lifecycleOwner: LifecycleOwner

The lifecycleOwner which controls the lifecycle transitions of the use cases.

cameraSelector: CameraSelector

The camera selector which determines the camera to use for set of use cases.

useCases: Array<UseCase!>

The use cases to bind to a lifecycle.

Returns
Camera

The Camera instance which is determined by the camera selector and internal requirements.

Throws
java.lang.IllegalStateException

If the use case has already been bound to another lifecycle or method is not called on main thread.

java.lang.IllegalArgumentException

If the provided camera selector is unable to resolve a camera to be used for the given use cases.

configureInstance

Added in 1.0.0
@ExperimentalCameraProviderConfiguration
java-static fun configureInstance(cameraXConfig: CameraXConfig): Unit

Perform one-time configuration of the ProcessCameraProvider singleton with the given CameraXConfig.

This method allows configuration of the camera provider via CameraXConfig. All initialization tasks, such as communicating with the camera service, will be executed on the java.util.concurrent.Executor set by setCameraExecutor, or by an internally defined executor if none is provided.

This method is not required for every application. If the method is not called and CameraXConfig.Provider is not implemented in Application, default configuration will be used.

Once this method is called, the instance configured by the given CameraXConfig can be retrieved with getInstance. CameraXConfig.Provider implemented in Application will be ignored.

Configuration can only occur once. Once the ProcessCameraProvider has been configured with configureInstance() or getInstance, this method will throw an IllegalStateException. Because configuration can only occur once, usage of this method from library code is not recommended as the application owner should ultimately be in control of singleton configuration.

Parameters
cameraXConfig: CameraXConfig

configuration options for the singleton process camera provider instance.

Throws
java.lang.IllegalStateException

if the camera provider has already been configured by a previous call to configureInstance() or getInstance.

getAvailableCameraInfos

Added in 1.1.0
fun getAvailableCameraInfos(): (Mutable)List<CameraInfo!>

Returns CameraInfo instances of the available cameras.

The available cameras include all the available cameras on the device, or only those selected through setAvailableCamerasLimiter

While iterating through all the available CameraInfo, if one of them meets some predefined requirements, a CameraSelector that uniquely identifies its camera can be retrieved using getCameraSelector, which can then be used to bind use cases to that camera.

Returns
(Mutable)List<CameraInfo!>

A list of CameraInfo instances for the available cameras.

getAvailableConcurrentCameraInfos

Added in 1.3.0
fun getAvailableConcurrentCameraInfos(): (Mutable)List<(Mutable)List<CameraInfo!>!>

Returns list of CameraInfo instances of the available concurrent cameras.

The available concurrent cameras include all combinations of cameras which could operate concurrently on the device. Each list maps to one combination of these camera's CameraInfo. For example, to select a front camera and a back camera and bind to LifecycleOwner with preview UseCase, this function could be used with bindToLifecycle.

Preview previewFront = new Preview.Builder()
                .build();
CameraSelector cameraSelectorPrimary = null;
CameraSelector cameraSelectorSecondary = null;
for (ListcameraInfoList : cameraProvider.getAvailableConcurrentCameraInfos()) {
    for (CameraInfo cameraInfo : cameraInfoList) {
        if (cameraInfo.getLensFacing() == CameraSelector.LENS_FACING_FRONT) {
            cameraSelectorPrimary = cameraInfo.getCameraSelector();
        } else if (cameraInfo.getLensFacing() == CameraSelector.LENS_FACING_BACK) {
            cameraSelectorSecondary = cameraInfo.getCameraSelector();
        }
    }
}
if (cameraSelectorPrimary == null || cameraSelectorSecondary == null) {
    return;
}
previewFront.setSurfaceProvider(frontPreviewView.getSurfaceProvider());
SingleCameraConfig primary = new SingleCameraConfig(
        cameraSelectorPrimary,
        new UseCaseGroup.Builder()
                .addUseCase(previewFront)
                .build(),
        lifecycleOwner);
Preview previewBack = new Preview.Builder()
        .build();
previewBack.setSurfaceProvider(backPreviewView.getSurfaceProvider());
SingleCameraConfig secondary = new SingleCameraConfig(
        cameraSelectorSecondary,
        new UseCaseGroup.Builder()
                .addUseCase(previewBack)
                .build(),
        lifecycleOwner);
cameraProvider.bindToLifecycle(ImmutableList.of(primary, secondary));
Returns
(Mutable)List<(Mutable)List<CameraInfo!>!>

list of combinations of CameraInfo.

getInstance

Added in 1.0.0
java-static fun getInstance(context: Context): ListenableFuture<ProcessCameraProvider!>

Retrieves the ProcessCameraProvider associated with the current process.

The instance returned here can be used to bind use cases to any LifecycleOwner with bindToLifecycle.

The instance's configuration may be customized by subclassing the application's Application class and implementing CameraXConfig.Provider. For example, the following will initialize this process camera provider with a Camera2 implementation from androidx.camera.camera2, and with a custom executor.

public class MyApplication extends Application implements CameraXConfig.Provider {
    @Override
    public CameraXConfig getCameraXConfig() {
        return CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
                   .setCameraExecutor(myExecutor)
                   .setSchedulerHandler(mySchedulerHandler)
                   .build();
    }

    . . .
}

If it isn't possible to subclass the Application class, such as in library code, then the singleton can be configured via configureInstance before the first invocation of getInstance(context), as in the following example.

class MyCustomizedCameraProvider {

    private static boolean configured = false;

    static ListenableFuture<ProcessCameraProvider> getInstance(Context context) {
        synchronized(MyCustomizedCameraProvider.class) {
            if (!configured) {
                configured = true;
                ProcessCameraProvider.configureInstance(
                    CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
                          .setCameraExecutor(myExecutor)
                          .setSchedulerHandler(mySchedulerHandler)
                          .build());
            }
        }
        return ProcessCameraProvider.getInstance(context);
    }
}

If no CameraXConfig.Provider is implemented by Application, or if the singleton has not been configured via configureInstance a default configuration will be used.

Returns
ListenableFuture<ProcessCameraProvider!>

A future which will contain the ProcessCameraProvider. Cancellation of this future is a no-op. This future may fail with an InitializationException and associated cause that can be retrieved by getCause. The cause will be a androidx.camera.core.CameraUnavailableException if it fails to access any camera during initialization.

Throws
java.lang.IllegalStateException

if CameraX fails to initialize via a default provider or a CameraXConfig.Provider.

hasCamera

Added in 1.0.0
fun hasCamera(cameraSelector: CameraSelector): Boolean

Checks whether this provider supports at least one camera that meets the requirements from a .

If this method returns true}, then the camera selector can be used to bind use cases and retrieve a instance.

isBound

Added in 1.0.0
fun isBound(useCase: UseCase): Boolean

Returns true if the UseCase is bound to a lifecycle. Otherwise returns false.

After binding a use case with bindToLifecycle, use cases remain bound until the lifecycle reaches a DESTROYED state or if is unbound by calls to unbind or unbindAll.

isConcurrentCameraModeOn

Added in 1.3.0
@MainThread
fun isConcurrentCameraModeOn(): Boolean

Returns whether there is a ConcurrentCamera bound.

Returns
Boolean

true if there is a ConcurrentCamera bound, otherwise false.

shutdownAsync

Added in 1.4.0-alpha04
@VisibleForTesting
fun shutdownAsync(): ListenableFuture<Void!>

Allows shutting down this ProcessCameraProvider instance so a new instance can be retrieved by getInstance.

Once shutdownAsync is invoked, a new instance can be retrieved with getInstance.

This method should be used for testing purposes only. Along with configureInstance, this allows the process camera provider to be used in test suites which may need to initialize CameraX in different ways in between tests.

Returns
ListenableFuture<Void!>

A ListenableFuture representing the shutdown status. Cancellation of this future is a no-op.

unbind

@MainThread
fun unbind(useCases: Array<UseCase!>): Unit

Unbinds all specified use cases from the lifecycle.

This will initiate a close of every open camera which has zero UseCase associated with it at the end of this call.

If a use case in the argument list is not bound, then it is simply ignored.

After unbinding a UseCase, the UseCase can be and bound to another Lifecycle however listeners and settings should be reset by the application.

Parameters
useCases: Array<UseCase!>

The collection of use cases to remove.

Throws
java.lang.IllegalStateException

If not called on main thread.

java.lang.UnsupportedOperationException

If called in concurrent mode.

unbindAll

Added in 1.0.0
@MainThread
fun unbindAll(): Unit

Unbinds all use cases from the lifecycle and removes them from CameraX.

This will initiate a close of every currently open camera.

Throws
java.lang.IllegalStateException

If not called on main thread.