Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BroadcastReceiver or Messenger via Handler

I have an IntentService which need to pass a message to an Activity. I know two ways of doing so.

  1. use sendBroadcast() at the Service side while registering a broadcastReciever at the Activity side which will receiver the message.

  2. passing a Messenger to the Service side, which will point to a Handler at the Activity side, which will be ready to receive that message from the service.

Which one is good for which purpose? Or both of them do the same?

like image 828
rayman Avatar asked Sep 10 '11 15:09

rayman


People also ask

What is the best approach to sticky broadcasts?

Calling the "sendStickyBroadcast" method within an app will cause a Sticky Broadcast message that will stay around within the system for receipt by other classes.

What does a BroadcastReceiver do?

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.

What is the difference between service and BroadcastReceiver in Android?

A Service receives intents that were sent specifically to your application, just like an Activity. A Broadcast Receiver receives intents that were broadcast system-wide to all apps installed on the device.

How do I check if BroadcastReceiver is registered?

Currently there is no way to check if a receiver is registered using the receiver reference. You have to unregister the receiver and catch the IllegalArgumentException that is thrown if it's not registered. This is ugly, and a boolean method to check if it's registered would be helpful.


1 Answers

If your IntentService does not know whether the activity will exist (e.g., might have been destroyed), or if there are multiple activities that might be in the foreground and would want to know about what's going on, I'd use sendOrderedBroadcast(). You can arrange to then also have a "backstop" BroadcastReceiver that could raise a Notification, if desired, as I outline in this blog post and demonstrate in this sample project.

Either of your techniques can work, though.

like image 171
CommonsWare Avatar answered Oct 16 '22 06:10

CommonsWare