Cancelling file download with httpclient and asynctask

android, android-asynctask, httpclient

Solution

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.

Problem

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

Original source