4

how can I stop threads safely?

 downloadThread = new Thread(new Runnable() {

   @Override
   public void run() {

  });
  downloadThread.start();
 }
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
Srinivas
  • 1,688
  • 8
  • 30
  • 51
  • 1
    This is a frequent question with frequent good answers like this: [How to abort a thread in a fast and clean way in Java](http://stackoverflow.com/questions/94011/how-to-abort-a-thread-in-a-fast-and-clean-way-in-java) – Andreas Dolk Nov 19 '10 at 07:28

3 Answers3

3

Instead of using normal thread to do background jobs if u will use Android sdk's AsyncTask, there you can find a cancel().

Ashis
  • 157
  • 2
  • 10
3

Interrupt the thread. In the run() method of the thread, check the value of isInterrupted() at the end of different logical blocks.

For instance, say your run() method can be broken up into three logical steps - creating a network connection, downloading an image and saving the image to a file. At the end of each of these steps, check for isCancelled() and stop the operation discarding all state at that point.

class NetworkFetcherTask extends AsyncTask<String, Void, Void>{
    public void doInBackground(String... params){
       String url = params[0];

       //Open connection if not cancelled
       if(isCancelled()){
           conn.close();
           return;
       }
       NetworkConnection conn = new NetworkConnection();


       //Download the image if not cancelled
       if(isCancelled()){
           conn.close();
           result.discard();
           return;
       }
       NetworkResult result = conn.fetchUrl(url);
       conn.close();

       //Save the image to a file if not cancelled
       if(isCancelled()){
          result.discard();
          return;
       }
       File file = new File();
       file.dump(result);
    }
}
Vikram Bodicherla
  • 7,133
  • 4
  • 28
  • 34
0

The easiest one seem to be setting isRunning to false.

dutt
  • 7,909
  • 11
  • 52
  • 85