How to schedule a background task
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 sle开发者_高级运维eping 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?
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.
精彩评论