取消的AsyncTask当用户presses后退按钮按钮、用户、AsyncTask、presses

2023-09-05 23:57:18 作者:梦该遗忘

我有一个AsyncTask的中,我在上preExecute显示ProgressDialog,并在onPostExecute再次隐藏它,像

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();
   }
};

的对话框撤销确实消失了,当我$执行AsyncTask的过程中p $ PSS取消按钮。

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

在这种情况下,我想运行一些code取消的AsyncTask以及(现在,甚至认为他ProgressDialog消失,在AsyncTask的继续运行,最终完成)。我试图得出我自己的类从ProgressDialog然后执行

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 */
   }
};

(或与OnCancelListener类似的东西),但是这只是从不被调用

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

任何想法?我只是需要一些机制来取消正在运行的AsyncTask的用户而ProgressDialog是显示。

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

推荐答案

我没有测试过这一点,但尝试是这样的:

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);
        }
};