简体   繁体   English

Android:最佳做法是使用AsyncTask定期加载Internet数据,并在加载失败时重试

[英]Android: Best practice to use AsyncTask to load internet data periodly and retry it when fail to load

I think it is common to load data and refresh it after some time as the data may change. 我认为加载数据并在一段时间后刷新它很常见,因为数据可能会更改。 My question is about how to load it periodly and how to retry the load action when load failed . 我的问题是有关如何定期加载它,以及在加载失败时如何重试加载操作。

I tried to use AsyncTask to get this job done, but my code is ugly, I want to know if there are some elegant solution to deal with this. 我试图使用AsyncTask来完成这项工作,但是我的代码很丑陋,我想知道是否有一些优雅的解决方案来解决这个问题。

I have some concerns: 我有一些担忧:

  1. Reload it rapidly when the first time it loads failed. 第一次加载失败时,请快速重新加载。 For the words rapidly , I mean I do not want to wait the next refresh time point to load it again, because the data is not loaded the first time, so I need to load it as soon as possible. 对于迅速 ,我的意思是我不想等待下一个刷新时间点再次加载它,因为数据不是第一次加载,所以我需要尽快加载它。
  2. When it successfully been loaded, start the periodic refresh action. 成功加载后,启动定期刷新操作。 If loaded failed in one action, do not need to retry it as the data have been loaded before, I could just wait for the next refresh. 如果加载操作失败,则无需重试,因为之前已加载数据,所以我可以等待下一次刷新。
  3. Stop retry action if it exist or the periodic refresh when the activity goes invisible 停止重试操作(如果存在)或在活动消失时定期刷新
  4. Resume retry action or the periodic refresh when the activity goes visible, still, retry action should happen rapidly , but the periodic refresh, I may want to check the last refresh time and to compare it with current time to determine whether the periodic refresh should start right now or later. 当活动变得可见时,继续重试操作或定期刷新,重试操作仍应迅速发生,但是定期刷新,我可能要检查上一次刷新时间并将其与当前时间进行比较,以确定是否应开始定期刷新现在或以后。

Sounds complex, any good code example for this requirements? 听起来很复杂,对此要求有很好的代码示例吗?

Simple follow the following steps 简单按照以下步骤

  1. Declare a timer task and schedule with Timer by method scheduleAtFixedRate(TimerTask task, long delay, long period) 通过scheduleAtFixedRate(TimerTask task, long delay, long period)声明计时器任务并使用Timer进行scheduleAtFixedRate(TimerTask task, long delay, long period)

    private class MyTask extends TimerTask { public void run(){ // Call to your async task by execute } } 私有类MyTask扩展了TimerTask {public void run(){//通过执行调用异步任务}}

  2. declare a Handler 声明处理程序

  3. When the Async Task done either in getting image or fail to do that.. send an empty message on the instance of the handler object 当异步任务完成获取图像或失败时..在处理程序对象的实例上发送空消息

  4. in handler cancle the async task 在处理程序中取消异步任务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM