Which is the best way to communicate between service and activity?

android

Solution

You can use `BroadcastReceiver` when you want the communication between `Service` and `Activity` in your application.

`Messenger`'s and `AIDL`'s are mainly used when your application needs to communicate to other processes(IPC). In this case your interface should have a `Service` which defines a `Handler` that responds to different types of `Message` objects.

Now the difference between `Messenger` and `AIDL` is pretty simple. When you use `Messenger`, it queues all requests into a single thread. So your `Service` doesn't have to be thread safe. If, you want your `Service` to handle multiple requests simultaneously, then you can use `AIDL` directly. In this case, your `Service` must be capable of multi-threading and be built thread-safe. In fact `Messenger` is implemented on the top of `AIDL`.

For better understanding look at Bound Services

You should also check the answer from BroadcastReceiver or Messenger via Handler

Problem

Now Activity can connect to services using one of three ways: - BroadcastReceivers - Messengers - AIDL I think that BroadcastReceivers is the easiest way to communicate but I'm wondering why and when to use other ways? or in other words in which cases messengers or AIDL will be the best practice to use than broadcastreceivers?

Original source

Related problems