4

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 ?

Community
  • 1
  • 1
Davim
  • 221
  • 2
  • 7
  • 2
    Read over [Ideal way to cancel an executing AsyncTask](http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask), it may help you. – Sam Dec 24 '12 at 01:45

3 Answers3

1
 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);
        }
};
mihirjoshi
  • 12,161
  • 7
  • 47
  • 78
0

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/

Miral Dhokiya
  • 1,720
  • 13
  • 26
Rui Gonçalves
  • 1,355
  • 12
  • 28
0

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;

    }
G M Ramesh
  • 3,420
  • 9
  • 37
  • 53