Possible Duplicate:
Ideal way to cancel an executing AsyncTask
When I developed an Android application, I used an AsyncTask to download something, I used a progressDialog to show the progress of this AsyncTask, now When I press the back button, I want to cancel this AsycTask, I invoked the AsycTask.cancel(), but it doesn’t work. How can I cancel a running AsyncTask ?
The most correct way to do it would be to check periodically inside
doInBackgroundif the task was cancelled (i.e. by callingisCancelled). From http://developer.android.com/reference/android/os/AsyncTask.html:Cancelling a task :
A task can be cancelled at any time by invoking
cancel(boolean). Invoking this method will cause subsequent calls toisCancelled()to returntrue. After invoking this method,onCancelled(Object), instead ofonPostExecute(Object)will be invokedafter
doInBackground(Object[])returns. To ensure that a task iscancelled as quickly as possible, you should always check the return
value of isCancelled() periodically from
doInBackground(Object[]), ifpossible (inside a loop for instance.)
Check also this blog post if you need more information: http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/