Camerax在服务中运行。如何在前台服务中获取生命周期所有者或在没有其情况下运行?

8

用例:我需要在服务中后台运行相机,而不需要任何活动或片段。

障碍:新的Camerax会话绑定到LifecycleOwner,但该服务没有。那么如何获取此对象或在没有它的情况下运行?

已尝试:我能够使用Camera2库做同样的事情,但我想知道是否也可以使用Camerax,因为Camera2 API可能会在未来被弃用。或者Google有意阻止用户在没有活动的情况下运行相机吗?

请建议。


https://medium.com/androiddevelopers/androids-camerax-jetpack-library-is-now-in-beta-bf4cf0cc3ea6 beta发布 - ArpitA
2个回答

5

你尝试过使用 LifecycleService 来扩展而不是普通的 Service 吗? 如果你还没有在 gradle 文件中添加 androidx.lifecycle:lifecycle-service:2.x.y 依赖,请先添加。 然后在调用 bindToLifecycle 方法时,只需将 this 作为参数传递即可:

class ExampleService : LifecycleService() {
    // here should be use case implementation
    ...
    processCameraProvider.bindToLifecycle(this, ...)

(免责声明:我没有测试过,所以不能保证100%可行。)
此外,在Android 11及以上版本中,您应该包含以下代码片段才能使其正常工作:following snippet
<manifest>
...
<service ... android:foregroundServiceType="camera" />

LifecycleService 有更多相关内容,请参见此处


服务的生命周期与活动片段不同。我想到了这个想法,但由于CameraX使用活动生命周期观察器,所以无法实现。请告诉我它是否适用于您。 - ArpitA
我针对的是 Android 6 到 9 版本。 - ArpitA
还可以阅读有关在后台实现相机的开发者答案: https://groups.google.com/a/android.com/g/camerax-developers/c/S-SVqEY1-Cg - MJegorovas

1

生命周期服务对我来说不起作用,但自定义ServiceLifeCycleOwner则可以很好地完成任务:

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
}

然后您可以像这样捕获图像:

    fun captureImage(cameraSelector: CameraSelector) {
    ...
       cameraProvider.unbindAll()
       cameraProvider.bindToLifecycle(lifeCycleOwner, cameraSelector, imageCapture)
       lifeCycleOwner.start()
    ...
    }

查看 Google example 了解如何使用CameraX,感谢Google提供如此简单而强大的API!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接