tags:

views:

174

answers:

1

There seems to be a couple of ways to go about having a background task being executed. My usecase is to have my app fetch a datafeed every x minutes, regardless of my gui is running, and regardless of whether the phone is sleeping or not.

I use an alarmmanager to schedule an intent matching a broadcastreceiver. in the onRecieve method i start a service (startService), which spawns an AsyncTask. The task fetches data and stores it and then stopSelf() the service.

in the onRecieve method i aquire a PARTIAL_WAKE_LOCK, before starting the service, and just before calling stopSelf() in the service, i release it again.

Is this really the best way to do it? Do i even need the service in this scenario?

I experience odd behaviour with this setup, where the setup works for hours and then suddenly stops, which makes it very hard to debug.

Does anyone have a simple foolproof method to achive the same end?

+3  A: 

I use an alarmmanager to schedule an intent matching a broadcastreceiver. in the onRecieve method i start a service (startService), which spawns an AsyncTask. The task fetches data and stores it and then stopSelf() the service.

I'd suggest using an IntentService instead of the AsyncTask/stopSelf() pattern, but otherwise this seems sound.

in the onRecieve method i aquire a PARTIAL_WAKE_LOCK, before starting the service, and just before calling stopSelf() in the service, i release it again.

That makes sense. I do much the same thing in my WakefulIntentService open source component.

Is this really the best way to do it?

You certainly seem close.

Do i even need the service in this scenario?

If what you need to do on the scheduled basis is guaranteed to only take a second or so, you could do that in the BroadcastReceiver. Otherwise, you need to have the work be done on a background thread, and BroadcastReceivers cannot fork background threads.

CommonsWare
aha! so i couldn't start my asynctask in the broadcastreciever? even if i aquire the wakelock in onrecieve and release it when the asynctask finishes? thanks for the info, and i guess i'll need to bughunt some more for my odd alarm stops
Wilken
"so i couldn't start my asynctask in the broadcastreciever?" I don't think so, but I haven't tried it. AsyncTask has its own thread pool, and it's *possible* that you can safely run an AsyncTask from a BroadcastReceiver.
CommonsWare
Thanks for the idea of using IntentService, didn't know about that. Now i have dropped my Service and the AsyncTask. Much more elegant.
Wilken