Home > Back-end >  How to catch the moment when the user leaves the app on Android?
How to catch the moment when the user leaves the app on Android?

Time:09-23

We want to execute some code (reset app state) when the user leaves the app (via back or start button tap). At first we tried to override Activity.onPause() for this purpose. However, onPause is also called when the user returns from a child Activity to the main one. So the app state is reset in this case as well. No good. What is the proper way to handle the monument when the app is paused?

Is there a way to tell if onPause was called after child Activity was closed?

CodePudding user response:

The best way to keep track of Application in background is to LifeCycleEvent

Use this library provided:-

implementation "androidx.lifecycle:lifecycle-common-java8:2.5.1" 

And keep this code in your BaseApplication:-

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        // do your stuff here
    }



@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun appInForeground() {
        // do your stuff here
    }

CodePudding user response:

Unless you have a specific workflow that requires resetting your app state when the app is closed, you'll be much better off doing it in onCreate() instead. That way you don't need to worry about why onPause() was called -- you'll be resetting the state only when the activity is initialized

  • Related