Question: I am running some tasks in UI part of my application.

While doing this lengthy task I need to show progress dialog so I am using AsysnTask to perform this.

When user pressed back button while progress bar going on , I need to cancel progress bar and I need to suspend that background work going on.

I am calling "dismiss()" on Progress Dialog so it's dismissed.

I am calling "cancel(true)" on my AsysnTask object, I thought my backgroung operations got stopped , but still it is executing though I have called "cancel(true)".

Then I have done some search on this issue and came to know that "cancel(true)" only called "onCancelled()" method of the AsyncTask.

I don't know what I have to write in my onCancelled() method so that my background operations got stopped immediately.

My doInBackground() method something look like this:

```
      protected void doInBackground()
         {
                  Statement  1;
                  Statement  2;
                 Statement  3;
                 Statement  4;
                 Statement  5;
                 Statement  6;
                 Statement  6;
                 Statement  7;
                 Statement  8;
                 Statement  9;

          }

```

let say in above code If got request to cancel after "Statement 4" then I don't want to execute reaming statements.

The above "doInBackground()" is just a example to make it understandable , In actual my "doInbackground()" method will have 100's of statements and I cant predict when I can get the request to cancel the operation.

Please help me how to do that.

Answer: 
In java threads are never terminated prematurely. You can kill a thread using native API, but Java API does not allow this anymore (even though there are some functions left that expose this interface, but they are not implemented and just throw exceptions).

Android exposes same philosophy, threads can not be terminated. You as developer is responsible for writing a thread in a such a way, so it reacts correctly when it is has been cancelled.

In your case you need to implement `doInBackground()` so it checks whether thread has already been cancelled or not. For example:

```
protected Void doInBackground()
{
       if(isCancelled()) return null;

       Statement  1;
       Statement  2;

       if(isCancelled()) return null;

       Statement  3;

       if(isCancelled()) return null;

       Statement  9;
 }

```

This is just an example, you can make a better implementation that checks thread state before executing next junk of its job.

By the way [`isCancelled()`](http://developer.android.com/reference/android/os/AsyncTask.html#isCancelled%28%29) was specifically designed for such use case. From documentation:

> 
> `public final boolean isCancelled ()` 
> 
> 
> Returns true if this task was cancelled before it completed normally.
>  **If you are calling cancel(boolean) on the task, the value returned by
>  this method should be checked periodically from
>  doInBackground(Object[]) to end the task as soon as possible**.
> 
> 
>
AsyncTasks have two important methods for this purpose: `cancel()` and `isCancelled()`.

Somewhere in your `doInBackground()`, you should be checking the value of `isCancelled()` and finish executing if it returns true. One important difference from normal execution is that once `doInBackground()` returns, `onCancelled()` is called on the UI thread, rather than `onPostExecute()`.

An example, a modified version of the simple task in the documentation:

```
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count && !isCancelled(); i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }

     protected void onCancelled(){
        showDialog("Operation was cancelled");
     }

 }

```

Take a look at "Cancelling a Task" in the official docs: <http://developer.android.com/reference/android/os/AsyncTask.html>