当用户按下后退按钮时取消 AsyncTask
我有一个 AsyncTask,其中在 onPreExecute 中显示一个 ProgressDialog,并在 onPostExecute 中再次隐藏它,就像
final class UploadTask extends AsyncTask {
ProgressDialog dialog = new ProgressDialog(...);
protected onPreExecute() {
dialog.show();
}
protected onPostExecute() {
dialog.hide();
}
};
对话框是可以取消的,当我在 AsyncTask 执行期间按下取消按钮时,对话框确实会消失。
发生这种情况时,我想运行一些代码来取消 AsyncTask (现在,即使他 ProgressDialog 消失,AsyncTask 仍继续运行并最终完成)。我尝试从 ProgressDialog 派生我自己的类,然后执行
setOnDismissListener(new OnDismissListener() {
@Override public void onDismiss(DialogInterface d) {
/* do something */
}
};
(或使用 OnCancelListener 类似的操作),但这根本不会被调用。
有什么想法吗?我只需要一些机制让用户在显示 ProgressDialog 时取消正在运行的 AsyncTask。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我还没有测试过这个,但尝试这样的事情:
I haven't tested this, but try something like this:
我想你正在寻找这个:onCancelled()
http://developer.android. com/reference/android/os/AsyncTask.html
I think you are looking for this: onCancelled()
http://developer.android.com/reference/android/os/AsyncTask.html