2

I have a file downloading android application.Here file is downloaded when user click on listview items.It works fine. Now,I want to cancel current file download and start next file while user taps on other items and another download is already progressing and show user confirmation before canceling the download task.

How can i do this?

Thanks in Advance

Devu Soman
  • 2,246
  • 13
  • 36
  • 57

3 Answers3

5

First, you must check in your AsyncTask

// in doInBackground, check if asynctask is canceled manually 
if (isCancelled()) break;

In your activiy, whenever you try to cancel, just cancel AsyncTask manually, and of course, start a new one to download another file!

mDownloadingTask.cancel(true);
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
2

Simply , you store your Asynctask to a variable:

mDownloadingTask = new Asynctask(){...};
mDownloadingTask.execute();

When you want to stop this task and start new one:

//close the current task if it # null
mDownloadingTask.cancel(true);
mDownloadingTask = null;
//Start new one
mDownloadingTask = new Asynctask(){...};
mDownloadingTask.execute();
Anh Nguyen
  • 413
  • 4
  • 15
0

Cancel(false) sets a flag, which you can check in doInBackGround() and stop your code from doing what its doing. cancel(true) does the same except it also interrupts the thread. See more info about interrupts here.

This is all good when you have a looped code in your task. Every iteration of the loop, you can check isCancelled().

But as in your question, some tasks like downloading a file do not use loops, perhaps you are just calling an external API method, so here, you are on the mercy of this blocking method. If well designed, it will throw an exception when interrupted, and the thread will terminate.

Also, have a look at a better implementation, SafeAsyncTask

S.D.
  • 29,290
  • 3
  • 79
  • 130