Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancelling file download with httpclient and asynctask

In my app I need to download files from url locations. I want to display progress of the download in a dialogbox (or optionally in the notification area). I've come across several good resources on this subject (something like http://progrnotes.blogspot.com/2010/09/c-android.html). Unfortunately, all the examples don't provide a clear indication on how to properly cancel a download per the user's request. So my question is actually quite simple:

Given an asynctask which downloads the file in the background (with httpclient) and displays a dialogbox with download progress and a cancel button, how do I can cancel the download and stop the background task when the button is pressed?

I know killing threads is generally not a good idea, so I will probably need to work with a 'cancel'-variable in my background thread. How do I communicate a stop signal from the button to the asynctask?

Regards, Ivo

like image 777
Ivo Avatar asked Feb 22 '11 15:02

Ivo


2 Answers

Have your button call AsyncTask.cancel(true) and then check isCancelled() from inside doInBackground(Params... params). In this manner, you can communicate to the background thread that the download should be cancelled, and you can take the appropriate steps to stop it.

like image 72
dbyrne Avatar answered Nov 06 '22 00:11

dbyrne


I would call cancel(true) on your AsyncTask object. This will interrupt your thread via normal interruption handling. You then can ask the AsyncTask if it isCancelled().

like image 3
mreichelt Avatar answered Nov 05 '22 23:11

mreichelt