Custom Lifecycle for CameraX

2.2k views Asked by At

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

1

There are 1 answers

0
Husayn Hakeem On BEST ANSWER

The ON_START and ON_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 even ON_RESUME). This will start the preview, the analyzer will begin receiving camera frames, and you'll be able to capture images. When the fragment's onPause() callback is invoked, you can move the custom lifecycle's state to ON_STOP. When the fragment is finally destroyed, make sure to move the lifecycle's state to ON_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.

class CameraFragment: Fragment() {

    private val customLifecycleOwner = CustomLifecycleOwner()

    override fun onViewCreated(view, savedState) {
        super.onViewCreated(view, savedState)
        // Initialize CameraX
        // Build use cases
        cameraProvider.bindToLifecycle(customLifecycleOwner, selector, useCases)
        customLifecycleOwner.startAndResume()
    }

    override fun onPause() {
        super.onPause()
        customLifecycleOwner.pauseAndStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        customLifecycleOwner.destroy()
    }
}