I am performing a network operation from a BroadcastReceiver
. This operation is being performed in the background and the app will not be running when this happens.
Which is better to use? A Service
or an AsyncTask
?
I am performing a network operation from a BroadcastReceiver
. This operation is being performed in the background and the app will not be running when this happens.
Which is better to use? A Service
or an AsyncTask
?
A BroadcastReceiver
object is only valid for the duration of the call to onReceive(). Once your code returns from this function, the system considers the object to be finished and no longer active. So it makes sense to just use an AsyncTask
or a Thread
here.
Also from the documentation :
In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver.
If this BroadcastReceiver was launched through a
<receiver>
tag, then the object is no longer alive after returning from this function. This means you should not perform any operations that return a result to you asynchronously -- in particular, for interacting with services, you should usestartService()
instead ofbindService()
. If you wish to interact with a service that is already running, you can usepeekService()
What this means is you can startService()
from your broadcast rcvr, pass the data required for your network operation thru an intent. The service will do the network operation. If the service is sticky, you can use peekService()
. But never should you bindService()
to a Broadcast rcvr.