Search code examples
androidbackground-processandroid-lifecycle

How to determine when Android application is being exited - application lifecycle instead of activity lifecycle


I have a multi-activity Android app which when started creates a ScheduledExecutorService. When the user Navigates away from the app the ScheduledExecutorService keeps running. What I'm trying to figure out is where can I signal the ScheduledExecutorService to stop just before the Application is stopped? I don't want to put it in each activity's onPause/onStop because I don't want to stop the ScheduledExecutorService between activities. I only want it to stop when the entire application is stopped. Any ideas?

I appreciate the help!


Solution

  • To do this you can use the new Android Lifecycle features. Instead of listening to Activity's Lifecycle just listen to the whole Application's Lifecycle. Just simply create an Application class and add the following code to it:

    public class MyApplication extends Application implements LifecycleObserver {
        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onEnterForeground(){
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onEnterBackground(){
        }
    }
    

    In your gradle file add this dependency:

    implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
    

    And you should get the effect you need.