2

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?

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
BlackberryChennai
  • 436
  • 1
  • 5
  • 18
  • 2
    possible duplicate of [Android: AsyncTask vs Service](http://stackoverflow.com/questions/6957775/android-asynctask-vs-service) – Octavian Helm Nov 08 '11 at 10:56
  • 2
    I'd argue it's not a duplicate, there are specific considerations when using a BroadcastReceiver. In this specific case, a Service should be used. – David Snabel-Caunt Nov 08 '11 at 11:03

2 Answers2

2

Better use a Service. AsyncTask is mainly not to block UI.

Vinay
  • 2,395
  • 3
  • 30
  • 35
2

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 use startService() instead of bindService(). If you wish to interact with a service that is already running, you can use peekService()

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.

Reno
  • 33,594
  • 11
  • 89
  • 102
  • The more relevant quote is `This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.` – David Snabel-Caunt Nov 08 '11 at 11:11
  • Hmm thanks, I missed that, you mean by using `registerReceiver()`? – Reno Nov 08 '11 at 11:18
  • The point really is that you should start a service in your BroadcastReceiver to do real work and return from the Receiver as soon as possible. You can pass data to the service via an Intent. – David Snabel-Caunt Nov 08 '11 at 11:54