Reputation: 315
I have an application, where I have put a connection to e certain service in a custom Application class, so that all activities can access it, but I need to close the service once my application is closed.
I want to send the bundled data just one time, not every time a single activity hits onPause/Destroy().
I also figured onTerminate() in the Application class is not always invoked.
Is there a better way to do this?
Upvotes: 1
Views: 238
Reputation: 10785
unfortunately, there is no callback / method to detect when your application process has stopped, or going to be stopped. @Alex suggestion to listen to the Activity lifecycle callbacks can be more tricky then it seems.
but if you want to detect this only for purposes of stopping running Service
, then this problem is not relevant, because if your process stooped, then all running services it owns is also stopped anyway!!
if you meant that you want to stop the service when the application is not in foreground (completely different thing..) then the solutions is different:
if you'll always use bindService()
instead of startService()
within the onResume
activity callback, and in the onPause()
stop it, then when your app would enter background - the service will be stopped automatically.
another option would be to use the Service callbacks to detect if currently there is bounded activity:
@Override
public IBinder onBind(Intent intent) {
mBoundedToActivity = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mBoundedToActivity = true;
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
mBoundedToActivity = false;
return super.onUnbind(intent);
}
Upvotes: 1
Reputation: 3382
If you are targeting API level 14 or above you can use the registerActivityLifecycleCallbacks to register a listener and count the launches/stops in onActivityResumed and onActivityStopped. When the counter is 0 then you know there is no more activity in the stack and you can close your service
Upvotes: 3