Cancel AsyncTask when user presses back button
Asked Answered
S

2

5

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.

Spy answered 1/11, 2010 at 18:55 Comment(1)
an example for cancelling an asynctask quicktips.in/correct-way-to-cancel-an-asynctask-in-androidFlagstone
K
14

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);
        }
};
Korney answered 1/11, 2010 at 20:38 Comment(1)
I decided to move the initialisation of the ProgressDialog into my constructor, which for some bizarre reason did the trick. Your method might work as well, haven't tried. In any case, if anyone is having the same problem: play around with the point at which you initialise the ProgressDialog.Spy
I
1

I think you are looking for this: onCancelled()

http://developer.android.com/reference/android/os/AsyncTask.html

Internationalize answered 1/11, 2010 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.