如何在 Android 中高效管理多个异步任务 [英] How to manage multiple Async Tasks efficiently in Android

查看:38
本文介绍了如何在 Android 中高效管理多个异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我必须对我的服务器进行六次 http 调用才能获取六个不同项目的数据.这些服务器调用不能组合在一起,它们就是这样.例如:如果您需要 GOOGLE 的报价信息,则向服务器发送请求以获取 google 的报价信息.接下来,如果您需要雅虎,那么您可以发起另一个 http 调用,依此类推.

情况如下:

  1. 现在我的最终用户想要比较 6 家不同的公司.
  2. 正如我提到的,我不可避免地要使用 6 个异步任务进行 6 个 http 调用.
  3. 当我收到每个异步任务响应时,我会用新数据刷新 UI.
  4. 如果我在很短的时间内刷新 UI 6 次,那将是一种糟糕的 UI 体验.
  5. 它给我的用户界面带来了不想要的闪烁效果.

我的问题:

  1. 如何在获得所有 6 个异步任务响应之前推迟刷新 UI?
  2. 我了解每项任务都是相互独立的.我应该运行一个 while 循环并等到收到所有响应吗?
  3. 有没有比 while 循环更好的方法来做到这一点,因为如果任何一个调用没有响应,那么我将永远等待.

注意:我猜 Android 1.6+ 会并行执行异步任务.

这更像是一个设计问题,如果您对此有任何帮助,我将不胜感激.

提前致谢

解决方案

我发现这个解决方案更适合我的问题.此链接描述了几种建立此方法的方法.1. ExecutorService2. ExecutoreService 和 CountDownLatch

ExecutoreService 和 CountDownLatch

I have scenario where I will have to make six http calls to my server to get the data for six different items. These server calls cant be combined and they are meant to be that way. Eg: If you need quote info for GOOGLE then send a request to server requesting for google's quote info. Next if you need yahoo's then you initiate another http call and so on.

Here is the situation:

  1. Now my end user wants to compare 6 different companies.
  2. As I mentioned its un-avoidable for me to make 6 http calls for which I do using 6 Async Tasks.
  3. As I get each one of the Async task response I will refresh the UI with new data.
  4. Its a bad UI experience if I refresh the UI 6 times in a very short period of time.
  5. Its give a flickering effect to my UI which is not desired.

My Question:

  1. How can I hold-off from refreshing the UI until I get all the 6 Async Task responses?
  2. I understand each task is independent of each other. Should I run a while loop and wait until I get all the responses?
  3. Is there a better way to do this rather than a while loop because if any one of the call doesn't respond then I will stuck waiting forever.

Note: I guess Android 1.6+ do execute Async tasks in parallel.

This is more of a design question and I would appreciate any help on this.

Thanks in advance

解决方案

I found this solution more appropriate to my problem. This link describes a couple of ways of establishing this. 1. ExecutorService 2. ExecutoreService and CountDownLatch

ExecutoreService and CountDownLatch

这篇关于如何在 Android 中高效管理多个异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆