简体   繁体   中英

How to create lifecycle aware components with Hilt?

Let's say, I have a MediaRecorder class that I will be using in a different fragment which looks this way:

class Recorder @Inject constructor(
    lifecycle: Lifecycle,
    private val mediaRecorder: MediaRecorder
) : LifecycleObserver {

    init {
        lifecycle.addObserver(this)
    }

    fun startRecording() {
        mediaRecorder.prepare()
        mediaRecorder.start()
    }

    fun stopRecording() {
        mediaRecorder.stop()
        mediaRecorder.release()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPauseEvent() {
        mediaRecorder.pause()
    }
}

I want to inject here the lifecycle of the fragment/activity that I will be using here.

How can I do that?

Try out via activity context

tailrec fun Context.activity(): Activity? = this as? Activity
    ?: (this as? ContextWrapper)?.baseContext?.activity()

class MyClass @Inject constructor(@ActivityContext context: Context) : LifecycleObserver {

    init {
        val activity = context.activity() as AppCompatActivity
        activity.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private fun onStart() {

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private fun onStop() {

    }
}

If this class is shared between fragments then add @ActivityScoped annotation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM