Search code examples
androidkotlinandroid-activityandroid-lifecycle

How to call method from MainActivity into LifeCycleObserver


I've followed a tutorial to build a timer application. The tutorial created methods in the MainActivity that creates and destroys the timer. Right now, I am trying to stop the timer when the user leaves the application. I am using a LifeCycleObserver to call when Lifecycle.Event.ON_STOP occurs and the app goes to the background.

I want to call a method called onTimerFinished() in the Main Activity when the user leaves the application

When I try to call the method in my LifeCycleObserver, it returns an error that it's an unresolved reference.

This is the LifecycleObserver where I am trying onTimerFinished

class ApplicationObserver() : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onBackground() {

        Log.d("myTag", "App closed")
        MainActivity.onTimerFinished()

    }
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onForeground() {
    }
}

This is the function onTimerFinished which is located in my MainActivity

private fun onTimerFinished(){
    timerState = TimerState.Stopped
    setNewTimerLength()
    progress_countdown.progress = 0
    PrefUtil.setSecondsRemaining(timerLengthSeconds,this)
    secondsRemaining = timerLengthSeconds
    updateButtons()
    updateCountdownUI()
}

When I move variables into the companion object for MainActivity, it doesn't seem to change the actual timer. Rather it changes the variables for the companion object.

How can I call this function in my LifecycleObserver


Solution

  • You can't call MainActivity private fun directly. You need a reference of it and have to make onTimeFinished method public.

    in MainActivity

    fun onTimerFinished(){
    timerState = TimerState.Stopped
    setNewTimerLength()
    progress_countdown.progress = 0
    PrefUtil.setSecondsRemaining(timerLengthSeconds,this)
    secondsRemaining = timerLengthSeconds
    updateButtons()
    updateCountdownUI()
    

    }

    lifecycleobserver

    class ApplicationObserver(mainActivity: MainActivity) : LifecycleObserver {
    
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onBackground() {
    
        Log.d("myTag", "App closed")
        mainActivity.onTimerFinished()
    
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onForeground() {
    }
    }
    

    you can pass this as parameter when you create ApplicationObserver object in MainActivity like

    val applicationObserver = ApplicationObserver(this)