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..
A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.
Assuming that rt is a Thread , just check rt. isAlive() . Alternatively, just use a boolean flag and set it to true right before you start your thread.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
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); } }
The method Thread.stop()
is deprecated, you can use Thread.currentThread().interrupt();
and then set thread=null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With