使用 AsyncTask 更新 ProgressDialog

发布于 2024-12-06 06:57:02 字数 176 浏览 0 评论 0原文

当我从网络获取数据时,我需要一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆で 2024-12-13 06:57:02

在不知道代码的完整细节的情况下,对我来说,听起来好像您可能以从未想过的方式使用 AsyncTask。

来自 文档:

此类允许执行后台操作并在 UI 线程上发布结果,而无需操作线程和/或处理程序。

在我看来,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:

This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

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...

小鸟爱天空丶 2024-12-13 06:57:02

这实际上完全取决于您的网络调用的参与程度。如果它们速度很快并且您没有提取大量数据,那么 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文