如何怎么停掉asynctask android

 private class DownloadFilesTask extends AsyncTask {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
 
首先欣赏一下官网上提供的实例,可以看到这条语句;
 if (isCancelled()) break;

这条语句的作用就是通过不断的检查当前AsyncTask的状态,立刻响应进行取消异步任务,具体可看下面最权威的官网解释;

官网上的解释是:

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically fromdoInBackground(Object[]), if possible (inside a loop for instance.)

附上一篇比较好的博客: http://blog.csdn.net/hitlion2008/article/details/7560878

你可能感兴趣的:(Android开发)