Android:取消异步任务 [英] Android: Cancel Async Task

查看:40
本文介绍了Android:取消异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用异步任务上传图片并获得一些结果.

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

上传图像时,我看到一个进度对话框,用 onPreExecute() 方法编写,如下所示:

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

好的,当我按下后退按钮时,显然由于 setCancelable(true) 对话框消失了.

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

但是(显然)异步任务不会停止.

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

那么我该如何解决这个问题?当我按下后退按钮时,我想取消对话和异步任务.有什么想法吗?

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

找到解决方案.请参阅下面的答案.

推荐答案

找到解决方案:我在 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();
          }
    });

这样当我按下后退按钮时,上面的 OnCancelListener 会取消对话框和任务.如果您想在按下后完成整个活动,也可以添加 finish() .请记住将异步任务声明为这样的变量:

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

这篇关于Android:取消异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆