LifecycleCameraProvider


@ExperimentalCameraProviderConfiguration
interface LifecycleCameraProvider : CameraProvider


Provides access to a camera which has its opening and closing controlled by a LifecycleOwner.

This allows configuring multiple instances with different Context and CameraXConfig. The use cases can be bound to different camera providers simultaneously, but only one LifecycleOwner can be active at a time.

The sample shows how to configure and create two camera providers differently.

import androidx.camera.camera2.Camera2Config
import androidx.camera.core.CameraSelector
import androidx.camera.core.CameraXConfig
import androidx.camera.lifecycle.LifecycleCameraProvider

val cameraProvider1 =
    LifecycleCameraProvider.createInstance(
        context1,
        CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
            .setCameraExecutor(executor1)
            .build(),
    )
cameraProvider1.bindToLifecycle(lifecycleOwner1, CameraSelector.DEFAULT_FRONT_CAMERA, useCase1)

// Switch to different lifecycle owner.

val cameraProvider2 =
    LifecycleCameraProvider.createInstance(
        context2,
        CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
            .setCameraExecutor(executor2)
            .build(),
    )
cameraProvider2.bindToLifecycle(lifecycleOwner2, CameraSelector.DEFAULT_BACK_CAMERA, useCase2)

Summary

Public companion functions

suspend LifecycleCameraProvider
createInstance(context: Context, cameraXConfig: CameraXConfig?)

Creates a lifecycle camera provider instance.

ListenableFuture<LifecycleCameraProvider>
createInstanceAsync(context: Context, cameraXConfig: CameraXConfig?)

Creates a lifecycle camera provider instance asynchronously.

Public functions

ConcurrentCamera

Binds list of SingleCameraConfigs to LifecycleOwner.

Camera
bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    sessionConfig: SessionConfig
)

Binds a SessionConfig to a LifecycleOwner.

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

Binds a UseCaseGroup to a LifecycleOwner.

Camera
bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    vararg useCases: UseCase?
)

Binds the collection of UseCase to a LifecycleOwner.

Boolean
isBound(sessionConfig: SessionConfig)

Returns true if the exact same instance of SessionConfig is bound to a lifecycle, false otherwise.

Boolean
isBound(useCase: UseCase)

Returns true if this UseCase is bound to a lifecycle or included in a bound SessionConfig, false otherwise.

Unit
unbind(sessionConfig: SessionConfig)

Unbinds the specified SessionConfig instance from the lifecycle provider.

Unit
unbind(vararg useCases: UseCase?)

Unbinds all specified use cases from the lifecycle provider.

Unit

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

Inherited functions

From androidx.camera.core.CameraProvider
open Unit
addCameraPresenceListener(
    executor: Executor,
    listener: CameraPresenceListener
)

Adds a listener for changes in camera presence.

open CameraInfo
getCameraInfo(cameraSelector: CameraSelector)

Returns the CameraInfo instance of the camera resulted from the specified CameraSelector.

open CameraInfo
getCameraInfo(
    cameraSelector: CameraSelector,
    sessionConfig: SessionConfig
)

Returns the CameraInfo instance of the camera resulted from the specified CameraSelector and SessionConfig.

Boolean
hasCamera(cameraSelector: CameraSelector)

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

open Unit

Removes a previously registered camera presence listener.

Inherited properties

From androidx.camera.core.CameraProvider
List<CameraInfo>

The CameraInfo instances of the available cameras.

Public companion functions

createInstance

suspend fun createInstance(context: Context, cameraXConfig: CameraXConfig? = null): LifecycleCameraProvider

Creates a lifecycle camera provider instance.

Parameters
context: Context

The Application context.

cameraXConfig: CameraXConfig? = null

The configuration options to configure the lifecycle camera provider. If not set, the default configuration will be used.

Returns
LifecycleCameraProvider

The lifecycle camera provider instance.

createInstanceAsync

Added in 1.5.0
fun createInstanceAsync(context: Context, cameraXConfig: CameraXConfig? = null): ListenableFuture<LifecycleCameraProvider>

Creates a lifecycle camera provider instance asynchronously.

Parameters
context: Context

The Application context.

cameraXConfig: CameraXConfig? = null

The configuration options to configure the lifecycle camera provider. If not set, the default configuration will be used.

Returns
ListenableFuture<LifecycleCameraProvider>

A ListenableFuture that will be completed when the lifecycle camera provider instance is initialized.

Public functions

bindToLifecycle

Added in 1.5.0
fun bindToLifecycle(
    singleCameraConfigs: List<ConcurrentCamera.SingleCameraConfig?>
): ConcurrentCamera

Binds list of SingleCameraConfigs to LifecycleOwner.

This function only supports combinations that are available via availableConcurrentCameraInfos. If the input list of SingleCameraConfigs does not match any of the supported combinations returned by availableConcurrentCameraInfos, IllegalArgumentException will be thrown. If cameras are already used by other UseCases, UnsupportedOperationException will be thrown.

To set up concurrent camera, call availableConcurrentCameraInfos 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 {@docRoot}training/camerax/architecture#lifecycles

There are two modes:

  1. Non-Composition mode: These SingleCameraConfigs have different preview and video capture use cases and there is no androidx.camera.core.CompositionSettings. In this mode, these previews and video captures can stream separately. CameraX doesn't perform any composition. You can also bind an extra image capture along with the preview and the video capture use cases.

  2. Composition mode: If the concurrent cameras are binding the same instances of preview and video capture use cases, the concurrent cameras video recording is supported. The concurrent camera preview stream will be shared with video capture and record the concurrent cameras streams as a composited stream. The androidx.camera.core.CompositionSettings can be used to configure the position of each camera stream and different layouts can be built. See androidx.camera.core.CompositionSettings for more details. The composition settings can also be updated dynamically by invoking androidx.camera.core.ConcurrentCamera.setCompositionSettings. The composition mode only supports preview and video capture. ImageCapture is currently not supported. androidx.camera.core.CameraEffect can be applied on the composited stream. However, the mirrorMode of VideoCapture will be ignored. This means the recorded video will have the same mirrorMode as the preview.

Parameters
singleCameraConfigs: List<ConcurrentCamera.SingleCameraConfig?>

Input list of SingleCameraConfigs.

Returns
ConcurrentCamera

Output ConcurrentCamera instance.

Throws
IllegalArgumentException

If the camera configs do not match any supported concurrent camera combination in availableConcurrentCameraInfos.

UnsupportedOperationException

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

bindToLifecycle

Added in 1.5.0
fun bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    sessionConfig: SessionConfig
): Camera

Binds a SessionConfig to a LifecycleOwner.

A SessionConfig encapsulates the configuration required for a camera session. This includes:

The state of the lifecycle will determine when the cameras are open, started, stopped and closed. When started, the use cases contained in the given SessionConfig receive camera data and the parameters of SessionConfig are used for configuring the camera including common field of view, effects and the session parameters.

Binding to a lifecycleOwner in state currently in Lifecycle.State.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.

Updates the SessionConfig for a given LifecycleOwner by invoking bindToLifecycle again with the new SessionConfig. There is no need to call unbind or unbindAll; the previous SessionConfig and its associated UseCases will be implicitly unbound. This behavior also applies when rebinding to the same LifecycleOwner with a different CameraSelector, such as when switching the camera's lens facing.

Important Restrictions:

Violating these restrictions will result in an IllegalStateException.

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.

import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.core.SessionConfig

val preview =
    Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider }
val imageCapture = ImageCapture.Builder().build()
val sessionConfig =
    SessionConfig(
        useCases = listOf(preview, imageCapture),
        viewPort = previewView.getViewPort(preview.getTargetRotation()),
        effects = listOf(effect1),
    )
// Starts the camera with the given effect and viewPort when the lifecycleOwner is started.
cameraProvider.bindToLifecycle(
    lifecycleOwner,
    CameraSelector.DEFAULT_BACK_CAMERA,
    sessionConfig,
)

// To apply a different effect, unbind the previous SessionConfig and bind the new SessionConfig
// with the new effect.
val sessionConfigNewEffect =
    SessionConfig(
        useCases = listOf(preview, imageCapture),
        viewPort = previewView.getViewPort(preview.getTargetRotation()),
        effects = listOf(effect2),
    )
// Make sures to unbind the previous sessionConfig before binding the new one
cameraProvider.unbind(sessionConfig)
cameraProvider.bindToLifecycle(
    lifecycleOwner,
    CameraSelector.DEFAULT_BACK_CAMERA,
    sessionConfigNewEffect,
)
Throws
UnsupportedOperationException

If the camera is configured in concurrent mode. For example, if a list of SingleCameraConfigs was bound to the lifecycle already.

IllegalStateException

if either of the following conditions is met:

bindToLifecycle

Added in 1.5.0
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.

Throws
UnsupportedOperationException

If the camera is configured in concurrent mode.

bindToLifecycle

Added in 1.5.0
fun bindToLifecycle(
    lifecycleOwner: LifecycleOwner,
    cameraSelector: CameraSelector,
    vararg useCases: 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 Lifecycle.State.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 android.hardware.camera2.CameraDevice.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.

Binding different use cases to the same lifecycle with different camera selectors that resolve to distinct cameras is an error, resulting in an exception.

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.

vararg useCases: 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
IllegalStateException

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

IllegalArgumentException

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

UnsupportedOperationException

If the camera is configured in concurrent mode.

isBound

Added in 1.5.0
fun isBound(sessionConfig: SessionConfig): Boolean

Returns true if the exact same instance of SessionConfig is bound to a lifecycle, false otherwise.

After binding a SessionConfig, this SessionConfig remains bound until the lifecycle reaches a Lifecycle.State.DESTROYED state or if is unbound by calls to unbind or unbindAll.

isBound

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

Returns true if this UseCase is bound to a lifecycle or included in a bound SessionConfig, false otherwise.

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

unbind

Added in 1.5.0
fun unbind(sessionConfig: SessionConfig): Unit

Unbinds the specified SessionConfig instance from the lifecycle provider.

This method will only unbind the session if the provided sessionConfig is the exact same instance that was previously used for binding.

This SessionConfig contains the UseCases to be detached from the camera. This will initiate a close of every open camera which has zero UseCase associated with it at the end of this call.

After unbinding the SessionConfig, another SessionConfig can be bound again and its UseCases can be bound to another Lifecycle.

Parameters
sessionConfig: SessionConfig

The sessionConfig that contains the collection of use cases to remove.

Throws
IllegalStateException

If not called on main thread.

UnsupportedOperationException

If called in concurrent mode.

unbind

Added in 1.5.0
fun unbind(vararg useCases: UseCase?): Unit

Unbinds all specified use cases from the lifecycle provider.

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 bound to another Lifecycle however listeners and settings should be reset by the application.

Parameters
vararg useCases: UseCase?

The collection of use cases to remove.

Throws
IllegalStateException

If not called on main thread.

UnsupportedOperationException

If called in concurrent mode.

unbindAll

Added in 1.5.0
fun unbindAll(): Unit

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

This will initiate a close of every currently open camera.

Throws
IllegalStateException

If not called on main thread.