Asynchronous Repeating Scheduled Task
Solution 1:
As other suggested in the comments. So let me elaborate it more.
DON'T USE AsyncTask. INSTEAD GO FOR IntentService ONLY.
- Make a class extends IntentService
- Use Alarm Manager to trigger a intent to your own service with specific action item
- Define a Interface to be used to notify client of this service.
- Maintain a list of these interface implemenation object provided by its client.
- in onHandleIntent(Intent intent) identify the call by checking action.
Initiate the data fetch request directly on intentService as the use worker thread to work and in the end call update delegate of the interface object list you maintained.
Make methods to Let Activity register and unregister from listening these updates.
- Which is actually adding the interface implementation provided by them in the list you maintained and remove from it when unregister gets called.
- make sure activity register itself in onResume and unregister itself in the onPause.
- Either use Repeating alarm or initiate one again in the end of single operation run. I hope it helps :)
Solution 2:
You can schedule the AsyncTask
to repeat at a fixed rate using Timer.scheduleAtFixedRate.
Solution 3:
Try this..
- Better use Service
to make this work again and again.
- Now you can use bound or unbound Service
. If you want the Service to be bounded to the Activity then use Bound Service else use UnBound Service.
- If would be even better to use IntentService
, as here you don't need the task keep running, but runs after certain amount of time.
See this link:
http://mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/
Solution 4:
I wrote an app that fires AsyncTask
s on a regular interval, except that they persist even when the app is closed. Anyway, here's what I had to do:
- Create a
PendingIntent
(viagetBroadcast()
) that contains anIntent
that contains an action. - Supply the
PendingIntent
to the system'sAlarmManager
and set the intervals. - Declare a
BroadcastReceiver
in the manifest to catch the action string supplied to theIntent
in no. 1. - In the
onReceive()
method of yourBroadcastReceiver
, fire theAsyncTask
.
Post a Comment for "Asynchronous Repeating Scheduled Task"