Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camerax run in service . How to get lifecycleowner or run without it inside a foreground service?

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

like image 500
ArpitA Avatar asked Mar 11 '20 06:03

ArpitA


2 Answers

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.

like image 84
MJegorovas Avatar answered Sep 18 '22 19:09

MJegorovas


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!

like image 43
Andoctorey Avatar answered Sep 16 '22 19:09

Andoctorey