Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I kill an Android thread completely?

Tags:

android

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..

like image 365
codereviewanskquestions Avatar asked May 31 '11 10:05

codereviewanskquestions


People also ask

How do you terminate a thread?

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.

How do I know if an android thread is running?

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.

How do you kill a specific thread in Java?

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.


2 Answers

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);   } } 
like image 54
Houcine Avatar answered Oct 14 '22 02:10

Houcine


The method Thread.stop() is deprecated, you can use Thread.currentThread().interrupt(); and then set thread=null.

like image 40
Atul Bhardwaj Avatar answered Oct 14 '22 01:10

Atul Bhardwaj