简体   繁体   中英

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.

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)

    private class MyTask extends TimerTask { public void run(){ // Call to your async task by execute } }

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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