Reputation: 3105
I need to create a service that will run as much as app will be running. I know that the most straightforward solution would be to bind service in my Application
class but this class does not have onDestroy
onStop
or onPause
methods so unbinding
is not possible... sadly... Other approach is to bind service to my base activity (and other activities will extend that activity) and for example onResume bind and onStop unbind
service. But then service will be always recreated... And that is not I want. Is it possible to have continuously running service and destroy it as soon as application closed? Here's the second approach (this code is in my base activity)
protected void onResume() {
super.onResume();
if (service == null && !isBound) {
bindService(new Intent(this, NetworkListenerService.class), mServiceConnection, BIND_AUTO_CREATE);
}
}
@Override
protected void onPause() {
super.onPause();
if (isBound) {
unbindService(mServiceConnection);
isBound = false;
}
}
Upvotes: 0
Views: 62
Reputation: 1894
Set the below attribute in your service tag in the manifest file,
<service android:name="service" android:stopWithTask="true"/>
adding this will call the ondestroy()
of the service when the task is removed.
Upvotes: 1