7

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

ArpitA
  • 721
  • 7
  • 17
  • https://medium.com/androiddevelopers/androids-camerax-jetpack-library-is-now-in-beta-bf4cf0cc3ea6 beta release – ArpitA Mar 18 '20 at 07:07

2 Answers2

4

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.

MJegorovas
  • 750
  • 1
  • 6
  • 18
  • Service has different lifecycle than activity fragment . I thought of this idea but was unable to implement since CameraX uses activity lifecycleobserver. Please let me know if it works for you . – ArpitA Jul 16 '20 at 05:42
  • I was targeting android 6 to 9 – ArpitA Jul 16 '20 at 05:43
  • Also read developer answer about camera implementation in background: https://groups.google.com/a/android.com/g/camerax-developers/c/S-SVqEY1-Cg – MJegorovas Jul 16 '20 at 06:57
1

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!

Andoctorey
  • 728
  • 9
  • 11