An analysis of Messenger Messenger usage and source code for Android application interprocess communication

Source: Internet
Author: User

1 Background

This knowledge point is a low goods, at the beginning actually want to in a previous article "Android asynchronous message processing mechanism and source analysis" as a point of knowledge analysis, but think and think and think it should be placed in the back of the process of communication analysis. And then the egg, or alone to write a piece of analysis it.

Mention of the message and handler in fact everyone is very familiar with, but when it comes to Messenger estimated that some people are not very common, and more can be the Messenger spelling error messager, thought is a message added R, of course, There are a lot of articles about messenger on the web, but personal analysis is always personal. Haha, no nonsense, to get to the other.

Messenger implements IPC Communication, the true principle of which is the use of aidl for communication, but unlike the direct use of aidl, Messenger takes advantage of the handler processing communication, so it is thread-safe (does not support concurrent processing) , while our usual aidl are non-thread-safe (support concurrent processing). So most of the time we don't have to deal with the Kua process and handle communication, so choosing Messenger is easier than aidl.

"Craftsman Joshui Http://blog.csdn.net/yanbober Reprint Please specify the source." Dot I started Android technology Exchange "

2 Base Instance

Analyze the source code before we look at a demo example, the core logic is that the client process clients send a message to the server process remote, the server process received the message after processing and then send back a message to the client, The whole process was implemented using Messenger Messenger and handler. Specific as follows:

Project Android Managed Files:

<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.example.yanbo.myapplication" >        <applicationandroid:allowbackup="true"android:icon="@ Mipmap/ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme " >                                        <activityandroid:name=". 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>        <!--": remote" means that in the application, when the service is needed, a new process "remote" is automatically created to represent the creation of the global process, and different applications share the process--        <service android:name=". Remoteservice "android:process=": remote ">                        <intent-filter>                <action android:name="Com.remote.RemoteService"/>            </intent-filter>        </Service>    </Application></manifest>

An independent process in the Project Server-side remote source code:

/** * Service in another process */ Public  class remoteservice extends Service {     Public Static Final intMsg_tag_remote =0x110; Public Static Final intMsg_tag_client =0x111;PrivateMessenger Mremotemessenger;PrivateRemotehandler Mremotehandler;Private intMcounter =0;@Override     Public void onCreate() {Super. OnCreate (); Mremotehandler =NewRemotehandler ();//Instantiate a messenger to pass in the current handlerMremotemessenger =NewMessenger (Mremotehandler); }@Override     PublicIBinderOnbind(Intent Intent) {return(Mremotemessenger = =NULL) ?NULL: Mremotemessenger.getbinder (); }Private  class remotehandler extends Handler {        @Override         Public void Handlemessage(Message msg) {Switch(msg.what) { CaseMsg_tag_remote://In order to pass the message back to the client side, get the client-side set of MessengerMessenger Clientmessenger = Msg.replyto;if(Clientmessenger! =NULL) {Try{//Note Obtain the first parameter, the previous article has an explanation, because the parameter target is not serializableClientmessenger.send (Message.obtain (NULL, Msg_tag_client, ++mcounter,0)); }Catch(RemoteException e)                        {E.printstacktrace (); }                    } Break;default:Super. Handlemessage (msg); Break; }        }    }}

A standalone process in the project client code:

 Public  class mainactivity extends Activity {    PrivateTextView Mtextview;PrivateMessenger Mremotemessenger =NULL;PrivateMessenger Mclientmessenger;PrivateClientHandler Mclienthandler;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Mtextview = (TextView) Findviewbyid (r.id.content_show);//Mclienthandler =NewClientHandler (); Mclientmessenger =NewMessenger (Mclienthandler); Bindservice (NewIntent ( This, Remoteservice.class), connection, context.bind_auto_create); }@Override    protected void OnDestroy() {Super. OnDestroy ();    Unbindservice (connection); }PrivateServiceconnection connection =NewServiceconnection () {@Override         Public void onserviceconnected(componentname name, IBinder service) {Mremotemessenger =NewMessenger (service);//Note obtain first parameter, previous article has explanationMessage message = Message.obtain (NULL, remoteservice.msg_tag_remote); Message.replyto = Mclientmessenger;Try{mremotemessenger.send (message); }Catch(RemoteException e)            {E.printstacktrace (); }        }@Override         Public void onservicedisconnected(componentname name) {}    };Private  class clienthandler extends Handler {        @Override         Public void Handlemessage(Message msg) {Switch(msg.what) { CaseRemoteservice.msg_tag_client:if(Mtextview! =NULL) {Mtextview.settext (msg.arg1+""); } Break;default:Super. Handlemessage (msg); Break; }        }    }}

Look, this is a super simple messenger use scenario, the specific process of comparing the image description such as:

I believe this picture does not need to explain what, this is also clear enough.

"Craftsman Joshui Http://blog.csdn.net/yanbober Reprint Please specify the source." Dot I started Android technology Exchange "

3 Messenger Source Analysis

It can be seen from the above example that, without considering concurrency, Messenger has won more than aidl in terms of code volume, engineering structure, complexity, and so on. Since it is so easy to use, then come to see his source bar, as follows we first concept viewing Mencius the entire core code of the Messenger class, and then elaborate. As shown below:

/** * Association handler Messenger to send and receive messages across processes Bridge class * Can see Messenger is a messenger, is an object * * Public Final  class Messenger implements parcelable {    //is actually the Aidl interface of the remote Messengerservice    Private FinalIMessenger Mtarget;//Create a messenger that points to target handler and then transport Messenger's send like Handler's SendMessage     Public Messenger(Handler target)    {mtarget = Target.getimessenger (); }//cross-process message, usually populated with the message parameter with Message.obtain (), or you can use your own new     Public void Send(Message message)throwsremoteexception {mtarget.send (message); }//Get Messenger binder, typically used on remote to get back     PublicIBinderGetbinder() {returnMtarget.asbinder (); }//If two Messenger equals indicates the same handler     Public Boolean equals(Object otherobj) {if(Otherobj = =NULL) {return false; }Try{returnMtarget.asbinder (). Equals ((Messenger) otherobj). Mtarget.asbinder ()); }Catch(ClassCastException e) {        }return false; }    ......//Get Getbinder the same Messenger object, typically used on client side to get     Public Messenger(IBinder target)    {mtarget = IMessenger.Stub.asInterface (target); }}

Using the above global preview of the Messenger class and the above instance use I'm sure you noticed that Messenger has two constructors, public Messenger (Handler target) and public Messenger (IBinder Target), it is clear that you already know that the parameter handler is a remote process instance method, and the parameter is IBinder as an instance method of the client process. In that case, let's get the constructor for the Messenger object from the server. Public Messenger (Handler target), as you can see, the code looks like this:

publicMessenger(Handler target) {    mTarget = target.getIMessenger();}

This constructor handler the Getimessenger method of the method, the source code in handler is as follows:

 Public  class Handler {......//In fact, for a handler object Getimessenger get Messenger is a singleton mode object    FinalIMessenger Getimessenger () {synchronized(Mqueue) {if(Mmessenger! =NULL) {returnMmessenger; }//Singleton mode get Messenger implementation class Messengerimpl objectMmessenger =NewMessengerimpl ();returnMmessenger; }    }//You can see that this is actually Messenger's AIDL implementation    Private Final  class messengerimpl extends imessenger. Stub {         Public void Send(Message msg) {The //send method really dispatched the handler SendMessage implementation to send the messageHandler. This. SendMessage (msg); }    }    ......}

As you can see, Getimessenger is a singleton object for each handler object, and the implementation class of this IMessenger object is Messengerimpl, can also see Messengerimpl is the implementation of Imessenger.stub class, this imessenger.stub is actually aidl file through the AAPT automatically generated in our Gen or Build Directory Server Interface sub-class only. Well, let's just make sure that's what we're saying, look at this. aidl file (frameworks/base/core/java/android/os/imessenger.aidl):

package android.os;  import android.os.Message;  /** @hide */  oneway interface IMessenger {      //可以看见,上面的MessengerImpl就实现了Messenger远程的send接口    void send(in Message msg);  }  

This is clear, the Messenger class Mtarget is actually a handler in a single case of IMessenger remote IPC interface Messengerimpl.

Then we look at the service in the implementation of the Onbind, which dispatched the messenger of the Getbinder method, this method of source code as follows:

publicgetBinder() {    return mTarget.asBinder();}

Can see, in fact Asbinder return is this, that is, oneself, that is, the service Messenger through the Onbind method to return to the client.

Then we temporarily go back to the client code of the above instance, we can find that the client process first task is to get the remote Messenger object instance by binding to the remote process service, the constructor is as follows:

publicMessenger(IBinder target) {    mTarget = IMessenger.Stub.asInterface(target);}

Hold the grass, this is not the way we usually get the service-side object implementation method? Yes, that's it. The client gets the Messenger object on the server and looks as if the client is new to an object, not really.

Then is the sending process, the message is first serializable, and then sent via Messenger send, and this send method above we also analyzed, and its implementation is through the handler SendMessage method to send, so no more explain, Back to the previous analysis of the handler and message process.

Overall can be found that, in fact, Messenger is not what high-end, frankly speaking is actually the Aidl two times package after the combination of handler so that users more convenient.

The entire Messenger principle is as follows:

"Craftsman Joshui Http://blog.csdn.net/yanbober Reprint Please specify the source." Dot I started Android technology Exchange "

4 Messenger Summary

After analyzing messenger, I believe I understand how it is, and know how to choose between Aidl and Messenger.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

An analysis of Messenger Messenger usage and source code for Android application interprocess communication

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.