Question: > 
> **Possible Duplicate:**  
> 
> [Ideal way to cancel an executing AsyncTask](https://stackoverflow.com/questions/2735102/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 ?

Answer: 
The most correct way to do it would be to check periodically inside `doInBackground` if the task was cancelled (i.e. by calling `isCancelled`). 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 to
 `isCancelled()` to return `true`. After invoking this method,
 `onCancelled(Object)`, instead of `onPostExecute(Object)` will be invoked
 after `doInBackground(Object[])` returns. To ensure that a task is
 cancelled as quickly as possible, you should always check the return
 value of isCancelled() periodically from `doInBackground(Object[])`, if
 possible (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/>
do the following on click of back button:

declare your Aynctask as global variable like this:

```
//AysncTask class
private contactListAsync async;

    if(async != null){

    async.cancel(true);

    async= null;

    }

```