0

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?

Pavel
  • 2,610
  • 3
  • 31
  • 50

1 Answers1

0

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
    }
  • Thank you for the help, Amit. However, your solution is for a different problem. Our goal is detecting the moment the user enters and leaves the main Activity of the app, while ignoring the returns from a child Activity. The code you proposed detects the moments when the app enters background and foreground states. Different stuff. – Pavel Sep 24 '22 at 05:33
  • buddy i coded that in BaseApplication, if you want it for just activity you code it in activity. It will workl – Amit Balani Sep 26 '22 at 09:44
  • We have a Foreground notification that makes the app running in the foreground even if Activity is in the background. – Pavel Sep 27 '22 at 06:31
  • Did you tried it? LifeCycle will be for activity not app if placed in activity. – Amit Balani Sep 27 '22 at 06:38
  • I have not tried it. Will do. Thanks, I hope it will work out. – Pavel Sep 29 '22 at 04:53