Last Updated:

Working with Messenger services in Android | With Example

Messenger services in Android

In the previous tutorial, we learned the basics of working with Services in Android. Now that we understand the difference between Service and IntentService, we can move on to the more complex topics of interprocess communication. If you're new to the basics of working with services, it's a good idea to review this content on Service and IntentService on Android.

In this article, we'll learn how to work with a service that uses Messenger for interprocess communication purposes.

Messenger on Android. Example of use

 

This article focused on related services that run in the background in different processes in a single-threaded or multithreaded environment.

Messenger is used to send messages in another process using IPC (Inter-Process Communication) thereby providing communication between the client and the server. Messenger will be associated with a handler, so all the work will take place on a single thread of the handler.

 

To bind a Service, you pass a reference to the Messenger instance to the method and pass the handler reference when you create the Messenger instance. Let's see a small example of creating a service that runs in a different process using Messenger that is associated with a handler:onBind()

As you can see from the code, the service uses Messenger to communicate with Activity. All data between Service and Acitivity is transferred in Bundle objects, which is very convenient for transferring various kinds of information. The service itself uses the IncomingHandler class, an inheritor of the Handler, to process the received message.

Now let's create an Activity to bind this service to send messages to the server, and server responses to the client using the Messenger handler:

In this application, we also need to have a ServiceConnection to the service to create a connection between the client and the server. ResponseHandler - The handler's successor will process Messenger's response and update the user interface.

Now let's add our Service in the application section:AndroidManifest.xml

In the layout file, let's add only an input field and a button to send a message:

Now let's run our program and look at the result:

As you can see, Messenger is a great way to communicate between the server and the client.

In the next lesson, we will learn how to work with AIDL in different processes. Subscribe to the news in social. networks and new articles.