Cancel AsyncTask when user presses back button

随声附和 提交于 2019-12-04 14:01:24

问题


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.


回答1:


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



回答2:


I think you are looking for this: onCancelled()

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



来源:https://stackoverflow.com/questions/4072117/cancel-asynctask-when-user-presses-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!