11

I am getting data from the server using AsyncTask. I need to update the data periodically.

Whats the best way to do it?

Macarse
  • 91,829
  • 44
  • 175
  • 230
Kunal P.Bharati
  • 949
  • 4
  • 11
  • 19

5 Answers5

5

You could use Timer class to schedule periodic task using TimerTask instead of AsyncTask

See :

http://developer.android.com/reference/java/util/Timer.html

http://developer.android.com/reference/java/util/TimerTask.html

And to update your UI you should follow this good tutorial :

http://android-developers.blogspot.com/2007/11/stitch-in-time.html

Kevin Grant
  • 2,311
  • 23
  • 17
Mathieu
  • 710
  • 1
  • 7
  • 10
4

Set an alarm with AlarmManager and call your AsyncTask in your AlarmReceiver class.

Macarse
  • 91,829
  • 44
  • 175
  • 230
  • Hi Macarse, Thanx for the answer. But can u tell me how can I call my AsyncTask class which is an inner class of my activity? – Kunal P.Bharati Sep 01 '10 at 12:25
  • it should be defined as `public static class` and call it with: `(new YourActivity.YourAsyncTask()).execute();` – Macarse Sep 01 '10 at 12:39
0

Just to state one of the possibilities. You could also use ScheduledThreadPoolExecutor class. It has, generally, more possibilities then TimerTask.

Prizoff
  • 4,486
  • 4
  • 41
  • 69
0

To elaborate upon macarse's response, you can indeed "set an alarm with AlarmManager and call your AsyncTask in your AlarmReceiver class."

The concern I raised in the linked post still stands: I don't know if there are any life cycle issues associated with instantiating an AsyncTask from a WakefulBroadcastReceiver, i.e., I don't know if the above solution can lead to MyAsyncTask being killed prematurely.

Community
  • 1
  • 1
user2768
  • 794
  • 8
  • 31
0

You can do it either on your onProgressUpdate() or on onPostExecute() based on your requirement.

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

http://developer.android.com/intl/de/reference/android/os/AsyncTask.html

DeRagan
  • 22,827
  • 6
  • 41
  • 50