SoFunction
Updated on 2025-03-11

Android uses Messenger to bind Service to various implementation methods

If you need to communicate between different processes, you can use Messenger in Service to implement in-process communication.

If you use this method, a Handler object needs to be defined in the Service (responsible for responding to the Message sent by the client).

Messenger can be shared with the client an IBinder object. The client sends a Message to the Service through this IBinder object, and the Handler object mentioned above is the basis of all this.

Note: Multithreading is not supported in this way for communication.

Then let’s take a look at using this method for communication!

Note: Service must be open to the public when declared, that is, android:exported="true", and this article is a Service started through Intent, so the Service can receive specific Actions during declaration.

1. Create a Handler object in the Service to process the Message sent from the client

2. Create a Messenger object based on the created Handler object

3. Use Messenger's getBinder method to get an IBinder object and reverse it in the Service's onBind method.

4. The client creates a Messenger object based on the IBinder parameter in onServiceConnected (refer to the Messenger constructor)

5. The client can use the Messenger object obtained in the previous step to send a Message to the Service.

After the above five parts, we can let the client communicate with the Service. After the client uses the Messenger object to send a Message to the Service, the Handler in the Service will respond to the message.

What is implemented above is only one-way communication, that is, the client sends a message to the Service. What should I do if I need the Service to send a message to the Client?

In fact, this is also very easy to implement. Let’s follow the above steps to achieve two-way communication~

6. Create a Handler object in the client to process messages sent by the Service

7. Create a client's own Messenger object based on the Handler object in the client

8. In step 5, we obtained the Service's Messenger object and sent a message to the Service through it. At this time, we assign the client's Messenger object to the replyTo field of the Message object to be sent

9. When the Service Handler processes Message, parse the client's Messenger and use the client's Messenger object to send a message to the client.

In this way, we realize two-way communication between client and service. The client and the Service have their own Handler and Messenger objects, so that the other party can send messages to themselves. It is worth noting that the client's Messenger is passed to the Service through the Message replyTo.