Cancel AsyncTask when user presses back button

Kasper Peeters picture Kasper Peeters · Nov 1, 2010 · Viewed 7.2k times · Source

I have an AsyncTask in which I show a ProgressDialog in the onPreExecute, and hide it again in onPostExecute, something like

final class UploadTask extends AsyncTask {
   ProgressDialog dialog = new ProgressDialog(...);

   protected onPreExecute() {
      dialog.show();
   }
   protected onPostExecute() {
      dialog.hide();
   }
};

The dialog is cancellable and indeed goes away when I press the cancel button during execution of the AsyncTask.

When this happens, I would like to run some code to cancel the AsyncTask as well (right now, even thought he ProgressDialog goes away, the AsyncTask keeps running and eventually completes). I tried deriving my own class from ProgressDialog and then do

setOnDismissListener(new OnDismissListener() {
@Override public void onDismiss(DialogInterface d) {
   /* do something */
   }
};

(or something similar with an OnCancelListener), but this simply never gets called.

Any ideas? I just need some mechanism for the user to cancel a running AsyncTask while a ProgressDialog is showing.

Answer

danh32 picture danh32 · Nov 1, 2010

I haven't tested this, but try something like this:

    final class UploadTask extends AsyncTask implements OnDismissListener{
       ProgressDialog dialog = new ProgressDialog(...);

       protected onPreExecute() {
           dialog.setOnDismissListener(this);
          dialog.show();
       }
       protected onPostExecute() {
          dialog.hide();
       }

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