Issue
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.
Answered By - Rafael Skubisz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.