androidandroid-lifecycle

Detect when my application is not active anymore


I wish to detect my application going into background. My app has an ongoing notification, this is how I can return into it.

Everyone keep recommending me to listen to Activity's lifecycle events like onPause, onActivate, etc.

However, when an app has multiple activities, lifecycle events can be hard to implement (as you have to implement into each and every activity), and moreover: during activity changes, this method can consider the application as inactive, while it's actually switching its activities.

What I need is to get an event when my application is deactivated (when I press home button for example).

How can I get this application-wise?


Solution

  • Implement ProcessLifecycleOwner to track app's lifecycle at the application level:

    import androidx.lifecycle.DefaultLifecycleObserver
    import androidx.lifecycle.LifecycleOwner
    import androidx.lifecycle.ProcessLifecycleOwner
    
    class AppLifecycleObserver : DefaultLifecycleObserver {
    
        override fun onStart(owner: LifecycleOwner) {
            // App entered foreground
        }
    
        override fun onStop(owner: LifecycleOwner) {
            // App entered background
        }
    }
    

    Initialize in your custom Application class

    ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())