6

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

Ivo
  • 519
  • 2
  • 9
  • 21

3 Answers3

3

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.

dbyrne
  • 59,111
  • 13
  • 86
  • 103
  • Thanks, sounds like the solution! ( I actually did see the cancel option in the reference, but I read complaints about reliability of this feature ). Checking often on isCancelled() in my thread should work. – Ivo Feb 22 '11 at 16:18
  • 2
    It just called the "OnCancelled" function but the downloader task still running isnt? I want a way to stop the downloading task.. how to do that – neobie Feb 15 '12 at 07:03
3

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().

mreichelt
  • 12,359
  • 6
  • 56
  • 70
  • Putting a `catch (InterruptedException e)` line in the AsyncTask says that `InterruptedException` is never thrown. So this seems not like a working solution. – Jarl Dec 17 '12 at 10:08
  • What is your reference that "This will interrupt your thread via normal interruption handling"? – Jarl Dec 17 '12 at 10:09
0

I would suggest you to go through this link for the dark-side of AsyncTasks: http://bon-app-etit.blogspot.in/2013/04/the-dark-side-of-asynctask.html .

Google has released a library called "Volley" that is used nowadays for faster and better networking .

It solves Bad points of AsyncTasks.

Canceling request using volley

Deep Shah
  • 1,334
  • 3
  • 20
  • 41