Search code examples
androidandroid-camerax

Multiple use cases with multiple lifecycles and same camera


I'd like to display preview in Activity and also periodicaly do image captures in LifecycleService in the background (using startForeground()).

So I've created a singleton with ProcessCameraProvider.

In Activity I do:

processCameraProvider.await().run {
    try {
        unbindAll()
        bindToLifecycle(
            this@MainActivity,
            CameraSelector.DEFAULT_BACK_CAMERA,
            Preview.Builder().build().also {
                it.setSurfaceProvider(binding.camera.surfaceProvider)
            }
        )
    } catch (e: Exception) {
        Timber.w(e)
    }
}
ContextCompat.startForegroundService(this, Intent(this, CaptureService::class.java))

And in the LifecycleService, I do:

processCameraProvider.await().bindToLifecycle(
    this@CaptureService,
    CameraSelector.DEFAULT_BACK_CAMERA,
    imageCapture
)

The periodic image capturing in the service works as expected, but as soon as I bind the LifecycleService, the preview stops. How can I fix this?

I'm using CameraX version 1.4.0-alpha01.


Solution

  • CameraX does not currently support binding multiple use case to same camera with different lifecycle. This is because CameraX using a single lifecycle to manage the camera state. Refer to this

    If you still need to bind multiple use case for the same camera with different lifecycle. You can try to create a custom lifecycle component that manage it camera lifecycle, then bind all of your use case to the custom lifecycle component, and start and stop the custom lifecycle component as needed.

    But, that workaround is not good practice, and it may lead to unexpected behavior, if you are not careful.