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: 
```
 class ImplementAsynctask extends AsyncTask implements OnDismissListener{
       ProgressDialog dialog = new ProgressDialog(ActivityName.this);

       protected onPreExecute() {
           //do something and show progress dialog
       }
       protected onPostExecute() {
          //cancel dialog after completion
       }

       @Override
        public void onDismiss(DialogInterface dialog) {
            //cancel AsycTask in between.
            this.cancel(true);
        }
};

```
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;

    }

```