用例:我需要在服务中后台运行相机,而不需要任何活动或片段。
障碍:新的Camerax会话绑定到LifecycleOwner,但该服务没有。那么如何获取此对象或在没有它的情况下运行?
已尝试:我能够使用Camera2库做同样的事情,但我想知道是否也可以使用Camerax,因为Camera2 API可能会在未来被弃用。或者Google有意阻止用户在没有活动的情况下运行相机吗?
请建议。
用例:我需要在服务中后台运行相机,而不需要任何活动或片段。
障碍:新的Camerax会话绑定到LifecycleOwner,但该服务没有。那么如何获取此对象或在没有它的情况下运行?
已尝试:我能够使用Camera2库做同样的事情,但我想知道是否也可以使用Camerax,因为Camera2 API可能会在未来被弃用。或者Google有意阻止用户在没有活动的情况下运行相机吗?
请建议。
你尝试过使用 LifecycleService 来扩展而不是普通的 Service
吗? 如果你还没有在 gradle 文件中添加 androidx.lifecycle:lifecycle-service:2.x.y
依赖,请先添加。 然后在调用 bindToLifecycle
方法时,只需将 this
作为参数传递即可:
class ExampleService : LifecycleService() {
// here should be use case implementation
...
processCameraProvider.bindToLifecycle(this, ...)
<manifest>
...
<service ... android:foregroundServiceType="camera" />
LifecycleService
有更多相关内容,请参见此处。
生命周期服务对我来说不起作用,但自定义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!