Reputation: 14008
I have a service that has its own thread running on background. I'd like to kill that service including the thread.
I created the thread like this and run it.
public class DaemonService extends Service {
private DaemonThread thread;
class DaemonThread extends Thread {
public void run()
{
runDaemon(mArgv.toArray(), mConfig);
}
}
public void onStart(Intent intent, int startId) {
thread = new DaemonThread();
thread.start();
}
}
How do I kill the service and the thread as well? I don't have to worry about data safety..
Upvotes: 33
Views: 83144
Reputation: 6717
The method Thread.stop()
is deprecated, you can use
Thread.currentThread().interrupt();
and then set thread=null
.
Upvotes: 7
Reputation: 187
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Thread.currentThread().interrupt();
}
Upvotes: 1
Reputation: 24181
to kill the thread , i think you can do like this :
myService.getThread().interrupt();
NOTE : the method Thread.stop()
is deprecated
EDIT : : try this
public void stopThread(){
if(myService.getThread()!=null){
myService.getThread().interrupt();
myService.setThread(null);
}
}
Upvotes: 42
Reputation: 76574
Do it in the service's onDestroy method
http://developer.android.com/reference/android/app/Service.html#onDestroy()
public void onDestroy(){
thread.stop();
super.onDestroy();
}
Then stop the service with stopService(); (this will invoke onDestroy());
Upvotes: 1
Reputation: 43108
use Context.stopService()
or stopSelf()
method of the Service.
Upvotes: 1