Julian A.
Julian A.

Reputation: 11450

Overlap in the responsibilities of BroadcastReceiver and IntentService

Is it correct that there's some overlap in the responsibilities of BroadcastReceiver and IntentService? By that, I mean that it would be redundant to set up a BroadcastReceiver that triggers an IntentService that performs some task that needs to be done. Since both respond to intents it's simpler to have just the IntentService respond directly to the intent without BroadcastReceiver serving as an intermediary.

Is this interpretation correct? Is it always correct? If not, please give an example of when it's incorrect.

Thanks much!

Upvotes: 0

Views: 76

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006664

I mean that it would be redundant to set up a BroadcastReceiver that triggers an IntentService that performs some task that needs to be done

Not only is that not necessarily redundant, it is a very common pattern.

Is this interpretation correct?

No.

please give an examples of when it's incorrect.

Either an Intent is used with sendBroadcast() or with startService(). If an Intent is used with sendBroadcast(), it is not possible for a service to respond to it directly. Similarly, if an Intent is used with startService(), it is not possible for a receiver to respond to it directly. So, in cases where somebody else wrote the code to use the Intent, you have to match up with how they used it. You cannot unilaterally "change the channel" that the Intent is used on.

Beyond that, onReceive() of a BroadcastReceiver is always called on the main application thread. You do not want to take any meaningful amount of time here, as it will freeze your UI if your UI happens to be in the foreground. And, once onReceive() returns, a manifest-registered receiver's instance is discarded, and your process may be terminated shortly thereafter. Hence, it is not safe for a BroadcastReceiver to fork its own background thread, as Android will ignore that thread and terminate your process. A common pattern for responding to system-sent broadcasts is to use a BroadcastReceiver, then have it delegate the work to an IntentService. In one fell swoop, you solve both problems:

  • IntentService does its heavy lifting in onHandleIntent(), called on a background thread
  • because it is a Service, having it running while doing that work will signal to the OS to let your process live a little while longer

Now, if you are the one creating the Intent and you are the one dispatching that Intent and you are the one consuming that Intent, and you want to have your code use startService() directly to invoke an IntentService, that is perfectly fine.

Upvotes: 1

Related Questions