使用 AsyncTask 更新 ProgressDialog
当我从网络获取数据时,我需要一个 AsyncTask 来运行我的 ProgressDialog。 我了解AsyncTask。但我在十几个地方都有网络通话。由于我对网络的调用来自不同的 Activity,如何为所有这些调用重用单个 AsynchTask 类?
这使我在活动中只要有网络调用的地方就重写了 AsyncTask。
I need a AsyncTask to run my ProgressDialog while I'm fetching data from the network.
I understand the AsyncTask. But I have the network calls in more than a dozen places. How can I reuse a single AsynchTask class for all these calls as my call to the network is from different Activity?
This made me rewrite the AsyncTask wherever in the Activities there is a network call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在不知道代码的完整细节的情况下,对我来说,听起来好像您可能以从未想过的方式使用 AsyncTask。
来自 文档:
在我看来,AsyncTask适合相对简单的异步任务,例如单个文件下载/流等。一旦需要更复杂的异步任务,那么也许可以利用完整的功能需要线程数。这一切都取决于设计和正确选择完成任务的可用工具......
Without knowing the full details of your code it does sound to me as though you might be using AsyncTask in a way it was never intended.
From the docs:
In my mind AsyncTask is suitable for relatively simple asynchronous tasks such as single file download/stream etc. Once there is a need for more complicated asynchronous tasks then perhaps utilising the full functionality of Threads is called for. It all comes down to design and correct choice of available tool for the task...
这实际上完全取决于您的网络调用的参与程度。如果它们速度很快并且您没有提取大量数据,那么 AsyncTask 就可以了。
最终,您需要做的是清理代码并确保没有重复任何逻辑。确保将所有重复的逻辑放在一个方法中。
为了避免为每个 Activity 重写 AsyncTask,请创建一个“父”Activity 类,在其中定义 AsyncTask(以及任何其他重复的逻辑)。然后让需要运行 AsyncTask 的活动扩展此活动。
但是,如果您的网络调用有所涉及,您可能需要研究另一种方法。您可能想要定义一个服务并将所有活动绑定到该服务。
It really all depends how involved your network calls are. If they are quick and you're not pulling a lot of data, then the AsyncTask will be fine.
Ultimately, what you need to do is clean up you code and make sure you're not repeating any logic. Make sure you're putting all the repeated logic in a single method.
So that you're not rewriting the AsyncTask for each Activity, make a "parent" Activity class where you define you're AsyncTask (and any other repeated logic). Then have the activities that need to run your AsyncTask extend this Activity.
If, however, your network calls are somewhat involved, you're probably going to want to look into another way of doing it. You may want to define a Service and bind all of your Activities to that service.