安卓:取消异步任务任务

2023-09-11 12:29:12 作者:曲终人也散

我用一个异步任务来上传图片,并获得了一定的成效。

I use an async task to upload an image and get some results.

在上传图片我看到一个进度对话框,写在preExecute()这样的方法:

While uploading the image I see a progress dialog, written in onPreExecute() method like this:

    protected void onPreExecute() { 
         uploadingDialog = new ProgressDialog(MyActivity.this); 
         uploadingDialog.setMessage("uploading"); 
         uploadingDialog.setCancelable(true);
         uploadingDialog.show();
    }

好吧,当我preSS后退按钮,显然对话框消失,因为setCancelable(真正的)。

Ok when I press the back button, obviously the dialog disappears because of the setCancelable(true).

不过,(显然)异步任务不会停止。

But (obviously) the async task doesn't stop.

那么,如何解决这一问题?我想取消对话框和异步任务时我preSS后退按钮。任何想法?

So how can I fix this? I want to cancel both dialog and async task when I press the back button. Any ideas?

编辑:找到了解决办法。看到我的回答以下。

FOUND THE SOLUTION. SEE MY ANSWER BELOW.

推荐答案

找到了解决办法: 我加了一个动作监听器uploadingDialog.show()这样的前:

FOUND THE SOLUTION: I added an action listener before uploadingDialog.show() like this:

    uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
          public void onCancel(DialogInterface dialog) {
              myTask.cancel(true);
              //finish();
          }
    });

这样,当我preSS后退按钮,上面OnCancelListener取消对话框和任务。你也可以添加结束(),如果你想结束背面pressed整个活动。请记住,你的声明异步任务,像这样的变量:

That way when I press the back button, the above OnCancelListener cancels both dialog and task. Also you can add finish() if you want to finish the whole activity on back pressed. Remember to declare your async task as a variable like this:

    MyAsyncTask myTask=null;

和执行你的异步任务是这样的:

and execute your async task like this:

    myTask = new MyAsyncTask();
    myTask.execute();