Kunal P.Bharati
Kunal P.Bharati

Reputation: 969

Best way to periodically executing AsyncTasks in Android

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

Whats the best way to do it?

Upvotes: 11

Views: 10917

Answers (5)

user2768
user2768

Reputation: 824

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.

Upvotes: 0

Prizoff
Prizoff

Reputation: 4575

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

Upvotes: 0

Mathieu
Mathieu

Reputation: 710

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

Upvotes: 5

Macarse
Macarse

Reputation: 93173

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

Upvotes: 4

DeRagan
DeRagan

Reputation: 22930

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

Upvotes: 0

Related Questions