15

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?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
rayman
  • 20,786
  • 45
  • 148
  • 246

1 Answers1

11

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    So basically you say in case I dont care whether my Activity is "alive" or not both techniques servs the same purpose equally ? – rayman Sep 11 '11 at 07:56
  • 3
    @rayman: You'll get a `RemoteObjectException` with the `Messenger` if the `Activity` is gone when you try sending the message, but since it's a checked exception, you need to handle that anyway. If there is exactly one component that needs to find out about the event, and you don't need to raise a `Notification` if that component is not around, a `Messenger` is the lightest-weight solution. – CommonsWare Sep 11 '11 at 12:30