I am trying to add a camera fragment using CameraX.but when i use this with viewPager(tablayout) i need camera to close when onPause() function called (as when i switch tab the camera should close ).but with default lifecycle of fragment it closes when fragment gets destroyed.
Therefore i tried to make a custom lifecycle (code shown below). but it is not working camera doesn't even open
class CustomLifecycle : LifecycleOwner {
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
init {
lifecycleRegistry.currentState = Lifecycle.State.CREATED
}
fun doOnResume() {
lifecycleRegistry.currentState = Lifecycle.State.RESUMED
}
fun doOnDestroy() {
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
binding cameraProvider to lifecycle
camera = cameraProvider.bindToLifecycle(
CustomLifecycle(), cameraSelector, preview, imageCapture, imageAnalyzer
)
I don't have any idea how to make it work
any suggestion will be appreciated
The
ON_START
andON_STOP
lifecycle events control when a bound use case becomes active and inactive. When a use case is active, it expects to start receiving data (frames) from the camera it's attached to. When a use case is inactive, it no longer expects data from the camera it's attached to.When you first bind your use cases to the custom lifecycle, you should immediately move its state to
ON_START
(or evenON_RESUME
). This will start the preview, the analyzer will begin receiving camera frames, and you'll be able to capture images. When the fragment'sonPause()
callback is invoked, you can move the custom lifecycle's state toON_STOP
. When the fragment is finally destroyed, make sure to move the lifecycle's state toON_DESTROY
in order to free up camera resources.In terms of code, you can take a look at a custom lifecycle owner used inside CameraX. You can use it as follows for your use case.