Cancel AsyncTask when user presses back button

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.

5
задан Kasper Peeters 1 November 2010 в 18:55
поделиться