Android uses Messenger for service IPC communication analysis

Source: Internet
Author: User


If you want to do IPC communication, write a aidl interface, write a service subclass, and then implement the Aidl interface as IBinder back to the activity interface layer.

If you do not want to write the Aidl interface file, only a single I-thread communication with the service we can use the Messenger class written by Android to handle, as well as the message to the service to communicate.


Write the basic code first:

public class MyService extends Service {Messenger messenger = null;public MyService () {} @Overridepublic void OnCreate () {s Uper.oncreate (); messenger = new Messenger (handler);//Instantiate an object and pass the handler incoming binding, UI MQ message detection}handler handler = new Handler () { public void Handlemessage (Android.os.Message msg) {LOG.D ("", "msg:" + Msg.what + ";" + msg.obj);}};/ * (non-javadoc) * @see android.app.service#onbind (android.content.Intent) */@Overridepublic IBinder onbind (Intent arg0 {return Messenger.getbinder ();//Return Binder Interface}}

Part of the code in MyActivity

<span style= "White-space:pre" ></span>messenger Messenger; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); BindService (new Intent (This,myservice.class), Conn, context.bind_auto_create);//Same as binding a connection}private serviceconnection conn = New Serviceconnection () {@Overridepublic void onservicedisconnected (ComponentName cn) {} @Overridepublic void Onserviceconnected (ComponentName cn, IBinder ibiner) {messenger = new Messenger (ibiner);//Get MESSENGERLOG.D in service (" "," OK Messenger connected ... ");}; public void sendmsg (int-What, String msg) {//This method is its own business message to send a message to the service with handler processing. if (Messenger = = null) {return;} Message MSG1 = Message.obtain (); msg1.what = What;msg1.obj = msg;try {messenger.send (MSG1);} catch (RemoteException e) {E.P Rintstacktrace ();}}

The code above is very simple.

The following look at the Messenger source code is actually a wrapper class, which itself is the IPC can be delivered by the object, because the use of the Parcelable interface.

    Public Messenger (Handler target) {//Handler here,        mtarget = Target.getimessenger (); What gets is actually the IMessenger interface inside the handler    } public    void Send (Message message) throws RemoteException {        mtarget.send ( message),//specific IMessenger interface sent    } public        IBinder Getbinder () {        return mtarget.asbinder ();    }    I've removed all the notes.

and see how handler source is sending messages.

    Final IMessenger Getimessenger () {        synchronized (mqueue) {            if (Mmessenger! = null) {                return mmessenger;            }            Mmessenger = new Messengerimpl ();//This implements the IMessenger remote IPC interface, Aidl            return mmessenger;        }    }    Private Final class Messengerimpl extends Imessenger.stub {//implementation in this place public        void Send (Message msg) {            handler.t His.sendmessage (msg);//There is still handler to send the message        }    }

It can be seen that imessenger this IPC interface contains the Send (Message msg) method, which essentially acquires the handler object in our MyService to send a message.


Imessenger.aidl
The contents are as follows

Package Android.os;import android.os.message;/** @hide */oneway interface IMessenger {    void send (in Message msg);}

The above source code is 4.1 version of the new source code has not been studied, this part should be consistent. Here is a simple sketch, a summary.




Android uses Messenger for service IPC communication analysis

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.