Android AsynTask 带有进度对话框取消
在我的 android 应用程序中,我使用带有进度对话框的 AsynTask(请等待登录...)通过我的网页(AsynTask 内的 Web 服务功能)登录用户,
我想在用户单击设备上的“后退”按钮时关闭进度对话框并取消 AsynTask 。
我找不到那种中断 AsynTask 的例子。我读到了有关 cancel(boolean) 的内容,但我不知道如何从 UI 调用。
谁能给我主意。
谢谢
In my android app I use AsynTask with Progress Dialog (Please wait login in ...) for logining user with my web page (web service function inside AsynTask)
I want to dismiss Progress Dialog and cancel AsynTask when user click on Back button on device.
I can't find that kind of example, for interrupting AsynTask. I read abouth cancel(boolean) but I don't know how to call from UI.
Can anyone give me idea.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
setCancelable(true) 方法设置是否可以使用 BACK 键取消对话框。
可以通过setOnCancelListener -> 执行整理代码onCancel 方法。
The setCancelable(true) method sets whether the dialog is cancelable with the BACK key.
You can execute finishing codes through setOnCancelListener -> onCancel method.
然后您需要做的就是当用户按下返回或主页时调用
handleOnBackButton()
。您可以使用onKeyDown()
方法来完成此操作。Then all you need is to call
handleOnBackButton()
when user presses back or home. You can do it usingonKeyDown()
method.您只需将 ProgressDialog 设置为可取消即可。当您单击“返回”按钮时,它将消失。
像这样:
您必须重写 onBackPressed 来关闭 ProgressDialog 并取消 AsyncTask
You just have to set your ProgressDialog cancelable. And it will disappear when you click "Back" button.
Like This :
You have to override onBackPressed to dismiss the ProgressDialog as well as cancel AsyncTask
我发现后退按钮事件被“显示”的 ProgressDialog 消耗,因此 Activity 不会对取消采取行动。我不得不将听众添加到对话框中:
没关系。
我发现使用活动的对话框管理并在OnCreatedIalog期间添加Ondismisslistener更加干净。解雇听众可以取消任务。无需保留对话框的引用,这是我们唯一需要收听用户取消的地方。
I have found that the back button event is consumed the ProgressDialog that is 'show'n, so the Activity does not get to act on the cancel. I had to add a listener to the dialog:
Nevermind.
I found it much cleaner to use the Activity's dialog management and add an onDismissListener during onCreateDialog. The dismiss listener can cancel the task. No need to hold a reference to the dialog and that is the only place we need to listen for user cancel.