Search code examples
androidkotlinandroid-lifecyclevolatileactivity-lifecycle

How would I stop a loop in Android, based on the app's life cycle


In the app, I am currently trying to have certain things happen depending on whether the app is in the background or the foreground. I am accomplising this using LifecycleObserver


@Volatile public var pause: Boolean = true

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onAppBackgrounded() {
    //App in background
    pause = true
    while(pause) {
        ///code running
    }
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onAppForegrounded() {
    pause = false
}

I try to end the loop inside of onAppBackgrounded() using a volatile Boolean, but this doesn't seem to work, as onAppForegrounded() will not happen while the loop in onAppBackgrounded() is still running. If anyone has any suggestions I'd really appreciate it.


Solution

  • Lifecycle functions are all called on the main thread, so onAppBackgrounded won't allow any other function be called on the main thread until it returns. You could run your loop in a new thread if it doesn't need to work with the main thread:

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onAppBackgrounded() {
        pause = true
        thread {
            while(pause) {
                ///code running
            }
        }
    }
    

    However, if your app is backgrounded, it can be killed at any time. You may want to run your action in a foreground service. Also keep in mind you could theoretically have multiple parallel threads started if there are rapid pause/resume cycles on your lifecycle object.