开发者

How to stop thread safely in android? [duplicate]

This question already has answers here: How do you kill a Thread in Java? (17 answers) How to properly stop the Thread in Java? (9 answers) Closed 6 years ago.

h开发者_开发问答ow can I stop threads safely?

 downloadThread = new Thread(new Runnable() {

   @Override
   public void run() {

  });
  downloadThread.start();
 }


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


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);
    }
}


The easiest one seem to be setting isRunning to false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜