Android 异步任务处理 UI
我是安卓开发新手。我想完成如下描述的任务:
- 调用外部类(另一个类将扩展
AsyncTask
)来解析xml
并接收json< 的主要活动/code> 通过请求 Web 服务并启动
ProgressDialog
。 - 该类在其
doInBackground
方法中执行xml
和json
解析。 - 解析完成后,在
onPostExecute
方法中,关闭在主 Activity 中设置的ProgressDialog
。 - 我可以通过将 ProgressDialog 对象传递给解析类并在其
onPostExecute
方法中消除同一对象来实现此目的。
我认为传递 UI 对象的实例作为参数并不是一个好的编程方法,我希望必须有其他方法来解决。
请建议。 谢谢
I am new to android development. I would like to accomplish a task described as follows:
- A main activty which calls external class(the other class would extend
AsyncTask
) to parsexml
and receivejson
by requesting to web service and starts aProgressDialog
. - The class performs
xml
andjson
parsing in itsdoInBackground
method. - In the
onPostExecute
method after parsing is complete, dismiss theProgressDialog
that was set in the main activity. - I could do this by passing the ProgressDialog object to the parsing class and dismissing the same object in its
onPostExecute
method.
I think passing an instance of UI object as argument is not a good approach to program, I hope there must be some other ways to work around.
Please suggest.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解耦这些的最简单方法是使用一个接口:
WorkDoneListener
):workDone()
。WorkDoneListener
并实现workDone()
以关闭对话框。WorkDoneListener
。将引用存储在成员字段中。onPostExecute
中,调用侦听器的workDone()
方法。The easiest way to decouple these is to use an interface:
WorkDoneListener
) with a single method:workDone()
.WorkDoneListener
and implementworkDone()
to dismiss the dialog.WorkDoneListener
. Stash the reference in a member field.onPostExecute
, call the listener'sworkDone()
method.Ted 的答案是,如果您的
AsyncTask
太大并且您想在其他文件中声明它,您应该做什么。但是,请记住,通常您在 UI 类中声明AsyncTask
:事实上,如果您仅在该活动中使用
AsyncTask
(我的意思是,如果您是不要在其他地方使用它),将AsyncTask
声明为内部类是一个很好的设计实践。Ted's answer is what you should do if your
AsyncTask
is too big and you want to declare it in other file. However, keep in mind that usually you declare theAsyncTask
inside your UI class:In fact, if you are using you
AsyncTask
from that activity only (I mean, if you are not using it anywhere else), declaring theAsyncTask
as a inner class is a good design practice.