Messenger of communication between Android processes

Source: Internet
Author: User

The mode of communication between Android processes can be done in the following two ways:

1 Android Interface Definition language (AIDL) 2 using the Messenger binding service

In this article we will learn how to communicate between processes using the Messenger binding service.

Android Aidl and Messenger differences

Using Messenger is the easiest way to perform interprocess communication because Messenger creates a queue that contains all the requests in a single thread, so that you do not have to design the service in a thread-safe manner. The pure Aidl interface sends multiple requests to the service at the same time, and the service must then deal with multithreading. Aidl is typically used in scenarios where services are designed into separate applications (i.e., where the client is not part of the same app), and Messenger is typically applied to a different process scenario in the same app.

The basic idea of Messenger

The server side (passive side) provides a service to handle client (active) connections, maintains a handler (specifically: Handler subclasses) to create Messenger, The binder that returns Messenger at Onbind (called the Getbinder () method of Messenger, which returns a IBinder object that the client will use as a parameter to create a Messenger object to communicate with the server).

Messenger Use steps

1. The server implements a handler, which receives callback 2 from each call from the client, creates a Messenger object using the handler instance of the 1th step as target (that is, the Messenger holds a reference to handler) 3, Using Messenger to create a IBinder (by invoking the Getbinder () method of Messenger), the server-side Onbind () method returns it to client 4, The client instantiates Messenger (referencing the handler instance of the server) using IBinder, and then uses the latter to send the Message object to server 5, where the server receives each message in its handler

In this way, the client does not invoke the "method" on the server side, and the message passed by the client is received by the server in its handler.

If you want the server to respond to the client, you also need to create a messenger in the client that holds the client handler implementation class, and when the client receives the onserviceconnected () callback, send () when the message is sent to the service The ReplyTo parameter of the method must contain the messenger of the client. The client can then receive a response message from the server in its handler implementation class.

Simple example

Androidmainfest.xml

<application    android:allowbackup= "true"    android:icon= "@drawable/ic_launcher"    android:label= "@ String/app_name "    android:theme=" @style/apptheme ">    <activity        android:name=" Yf.exam.client.MainActivity "        android:label=" @string/app_name ">        <intent-filter>            <action Android:name= "Android.intent.action.MAIN"/>            <category android:name= "Android.intent.category.LAUNCHER" />        </intent-filter>    </activity>    <service android:name= ". Messengerservice "android:process=": Custom_process "/></application>

In the above configuration file, the service's Android:process property is used to start the service in a separate process, as seen in the slice:

The layout file is simple and there is only one button to send a message to the server and display the service-side response content, which is no longer given here.

Client: mainactivity

public class Mainactivity extends Activity {private static final int reply_msg_id = 2;    Private Boolean mserviceconnected = false;    Private Button btn = null;    Messenger private Messenger Mboundservicemessenger = null for sending messages to the service side;    Messenger private final Messenger Mreceivemessenger = new Messenger (new Receivemesshandler (this)) for receiving service delivery messages; Private Serviceconnection conn = new Serviceconnection () {@Override public void onservicedisconnected (Com            Ponentname name) {Mboundservicemessenger = null;        mserviceconnected = false; } @Override public void onserviceconnected (componentname name, IBinder service) {Mbounds            Ervicemessenger = new Messenger (service);        Mserviceconnected = true;    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); BTN = (Button) fiNdviewbyid (R.id.button);        Bindservice (New Intent (this, messengerservice.class), Conn, context.bind_auto_create);                Btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                    if (mserviceconnected) {//Gets the Message object msg = Message.obtain (null, 1, 0, 0); try{//replyto parameter contains client messenger Msg.replyto = mreceivemess                        Enger;                    Send Message Mboundservicemessenger.send (msg) to the service side;                    }catch (RemoteException re) {re.printstacktrace ();    }                }            }        });        } @Override protected void OnDestroy () {Super.ondestroy ();            if (mserviceconnected) {unbindservice (conn);        mserviceconnected = false; }}/** * Client implements a handler for receiving the response returned by the server * @author AdminisTrator * * */Static Class Receivemesshandler extends handler{//holds weak references to current activity to avoid memory leaks private fi        NAL weakreference<mainactivity> mactivity;        Public Receivemesshandler (mainactivity activity) {mactivity = new weakreference<mainactivity> (activity); } @Override public void Handlemessage (Message msg) {switch (msg.what) {case REP                LY_MSG_ID:Toast.makeText (Mactivity.get (), Msg.getdata (). getString ("MSG"), Toast.length_short). Show ();            Break }        }    }}

Server side: Messengerservice.java

public class Messengerservice extends Service {private static final int reply_msg_id = 2;    private static final int msg_id = 1;        Static class Boundservicehandler extends handler{private final weakreference<messengerservice> mservice; Public Boundservicehandler (Messengerservice service) {mservice = new weakreference<messengerservice>        (service);                } @Override public void Handlemessage (Message msg) {switch (msg.what) {case msg_id:                Messenger Replymessenger = Msg.replyto;                Message replymsg = Message.obtain (null, reply_msg_id);                Message content that responds to the client bundle B = new bundle ();                B.putstring ("msg", "This was the message reply from service");                Replymsg.setdata (b);                try{replymessenger.send (replymsg);                }catch (RemoteException re) {re.printstacktrace ();     }           Break            Default:super.handleMessage (msg);    }}} private final Messenger Mmessenger = new Messenger (new Boundservicehandler (this)); @Override public IBinder onbind (Intent Intent) {Toast.maketext (Getapplicationcontext (), "binding", toast.length        _short). Show ();    return Mmessenger.getbinder (); }}

  

Messenger of communication between Android processes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.