Use case : is that I have to run camera in background inside a service without any activity or fragment
Blocker : New camerax session is bind to lifecycleowner but the service don't have any .So how to get this object or run without it ?
Already tried : The same thing I am able to do with Camera2 library but I want to know whether it is possible with Camerax also because Camera2 api might get deprecated in future . Or google is intentionally trying to block user from running camera without activity?
Please suggest
Have you tried extending LifecycleService instead of regular Service
? For that you'll need to add androidx.lifecycle:lifecycle-service:2.x.y
as a dependency in your gradle file if you haven't already. Then, when you call bindToLifecycle
method you just pass this
as a parameter and it should work:
class ExampleService : LifecycleService() {
// here should be use case implementation
...
processCameraProvider.bindToLifecycle(this, ...)
(disclaimer: didn't test this so I'm not 100% sure).
Also, starting with Android 11 you should include following snippet for this to work:
<manifest>
...
<service ... android:foregroundServiceType="camera" />
More on LifecycleService
here.
LifecycleService doesn't work for me but custom ServiceLifeCycleOwner makes job great:
class ServiceLifeCycleOwner : LifecycleOwner {
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
init {
lifecycleRegistry.currentState = Lifecycle.State.CREATED
}
fun start() {
lifecycleRegistry.currentState = Lifecycle.State.STARTED
}
fun stop() {
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
}
override fun getLifecycle(): Lifecycle = lifecycleRegistry
}
Then you can capture image like this:
fun captureImage(cameraSelector: CameraSelector) {
...
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(lifeCycleOwner, cameraSelector, imageCapture)
lifeCycleOwner.start()
...
}
See google example how to use cameraX and thank you google for such simple and powerful api!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With