Reputation: 10708
I am using the following statement to stop a download service (that extends IntentService) running in the background:
context.stopService(intent);
But this statement is not calling the onDestory() method of service immediately, It is taking sometime to call onDestroy() method of service.
@Override
public void onDestroy() {
Log.d("JSLog", "on destroy called");
super.onDestroy();
}
What should I do that after hitting the stopService() statement, it should immediately called onDestroy() method of the service.
Upvotes: 4
Views: 4777
Reputation: 18738
In my case, I followed the tutorial at Android Developers, which uses a ServiceConnection
. In the example code, they call unbindService()
but never stopService()
. So I added a call to stopService()
to stop it, but still onDestroy()
never got called.
From the documentation of Context.stopService():
Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed.
I interpreted this as it's okay to call stopService()
or stopSelf()
first, and then unbindService()
afterwards (I'm using BIND_AUTO_CREATE
) - and that the service would be stopped/destroyed upon calling unbindService()
.
But it turns out that this isn't the case. When I moved things around so that I'm calling unbindService()
first and stopService()
after that, my onDestroy()
gets called immediately.
Upvotes: 10
Reputation: 10938
This is expected behaviour, a Service won't immediately be destroyed once stopped just like an Activity might not be immediately destroyed once finished (unless you finish inside onCreate).
Upvotes: 1
Reputation: 49
the intentService has new Thread,when u stop the service the new thread won't stop right now,if u want stop the thread right now ,i will extends service and new Thread in the service,when u need stop the service just need interrupt the thread.
Upvotes: 2