Messenger of Android Process communication

Source: Internet
Author: User

Write it in front.

I wrote an article in front of-android learn the aidl of remote service, talk about cross-process multithreading communication, we use AIDL technology to achieve. But at this point, Messenger is a very good choice for us as long as we can ask for cross-process communication without using multi-threading.

Messenger Instance Server side:

Messengerservice.java

ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.Handler;ImportAndroid.os.IBinder;ImportAndroid.os.Message;ImportAndroid.os.Messenger;ImportAndroid.os.RemoteException;ImportAndroid.util.Log;ImportAndroid.widget.Toast; Public  class messengerservice extends Service {     Public Static FinalString TAG ="Messengerservice"; Public Static Final intMsg_send_to_server =1; Public Static Final intMsg__reply_from_server =2;FinalMessenger Mmessenger =NewMessenger (NewIncominghandler ()); Class Incominghandler extends Handler {@Override         Public void Handlemessage(Message msg) {Switch(msg.what) { CaseMSG_SEND_TO_SERVER:LOG.I (TAG,"Msg_send_to_server:"+"--MSG.ARG1:"+msg.arg1+"--MSG.ARG2:"+MSG.ARG2);Try{Message messagereplytoclient =NewMessage ();                        Messagereplytoclient.what = Msg__reply_from_server;                        MESSAGEREPLYTOCLIENT.ARG1 = MSG.ARG2;                        MESSAGEREPLYTOCLIENT.ARG2 = MSG.ARG1;                    Msg.replyTo.send (messagereplytoclient); }Catch(RemoteException e) {//TODO auto-generated catch blockE.printstacktrace (); } Break;default:Super. Handlemessage (msg); }        }    }@Override     PublicIBinderOnbind(Intent Intent) {//TODO auto-generated method stubToast.maketext (Getapplicationcontext (),"Binding", Toast.length_short). Show ();returnMmessenger.getbinder (); }}
Client Side Mainactivity.java
ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.IBinder;ImportAndroid.os.Message;ImportAndroid.os.Messenger;ImportAndroid.os.RemoteException;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;Importandroid.app.Activity;ImportAndroid.content.ComponentName;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.content.ServiceConnection; Public  class mainactivity extends Activity {     Public Static FinalString TAG ="Mainactivity"; Public Static Final intMsg_send_to_server =1; Public Static Final intMsg__reply_from_server =2;PrivateMessenger Mmessenger;BooleanMbound;PrivateTextView textviewshowconnectstate;PrivateTextView Textviewmessagesendtoservice;PrivateTextView Textviewmessagereceiverfromservice;PrivateButton button;PrivateMessenger mmessengerreceive =NewMessenger (NewMyHandler ()); Class MyHandler extends Handler {@Override         Public void Handlemessage(Message msg) {Switch(msg.what) { CaseMSG__REPLY_FROM_SERVER:LOG.I (TAG,"Msg__reply_from_server:"+"--msg.arg1="+msg.arg1+"--msg.arg2="+MSG.ARG2); Textviewmessagereceiverfromservice.settext ("Msg:server-->client:"+"--msg.arg1="+msg.arg1+"--msg.arg2="+MSG.ARG2); Break;default:Super. Handlemessage (msg); }        }    }PrivateServiceconnection mconnection =NewServiceconnection () { Public void onserviceconnected(ComponentName className, IBinder service) {Mmessenger =NewMessenger (service); Mbound =true; Textviewshowconnectstate.settext ("Service Connect"); } Public void onservicedisconnected(ComponentName className) {Mmessenger =NULL; Mbound =false; Textviewshowconnectstate.settext ("Service Disconnect"); }    }; Public void SendMessage(View v) {if(!mbound)return;//Create and send a message to the service with using a supported ' what ' value        intArg1 = (int) (Math.random () * -);;intArg2 = (int) (Math.random () * -);; Message msg = Message.obtain (NULL, Msg_send_to_server, Arg1, arg2);        Msg.replyto = mmessengerreceive; Textviewmessagesendtoservice.settext ("Msg:client-->server:"+"--msg.arg1="+msg.arg1+"--msg.arg2="+MSG.ARG2);Try{mmessenger.send (msg); }Catch(RemoteException e)        {E.printstacktrace (); }    }@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    Init (); }Private void Init() {//TODO auto-generated method stubTextviewshowconnectstate = (TextView) Findviewbyid (r.id.textviewshowconnectstate);        Textviewmessagesendtoservice = (TextView) Findviewbyid (R.id.textviewmessagesendtoservice);        Textviewmessagereceiverfromservice = (TextView) Findviewbyid (R.id.textviewmessagereceiverfromservice);    Button = (button) Findviewbyid (R.id.button); }@Override    protected void OnStart() {Super. OnStart (); Bindservice (NewIntent ("Com.android.ACTION.MessengerService"), Mconnection, context.bind_auto_create); }@Override    protected void OnStop() {Super. OnStop ();if(Mbound)            {Unbindservice (mconnection); Mbound =false; }    }}

Our client sends a message to the server encapsulated in the SendMessage method:

mMessenger.send(msg);

So how to respond to messages that are sent back from the server, the key is to correlate the message msg that the client sends to the server with the Messenger mmessengerreceive that the callback handles:

msg.replyTo = mMessengerReceive;
Layout file:

Activity_main.xml

<relativelayout xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="Match_parent"android:layout_height="Match_parent"Android:paddingbottom="@dimen/activity_vertical_margin"android:paddingleft="@dimen/activity_horizontal_margin"android:paddingright="@dimen/activity_horizontal_margin"android:paddingtop="@dimen/activity_vertical_margin"tools:context=". Mainactivity "> <textview android:id="@+id/textviewshowconnectstate"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"/> <button android:id="@+Id/button"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:layout_below="@id/textviewshowconnectstate"android:onclick="SendMessage"android:text="Click Send Message to Server"/> <textview android:id="@+id/textviewmessagesendtoservice"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:layout_below="@id/button"/> <textview android:id="@+id/textviewmessagereceiverfromservice"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:layout_below="@id/textviewmessagesendtoservice"/></relativelayout>

From the source and, as we can see, this demo is sending a message from the client to the server, The server exchanges the value of the MSG.ARG1 and msg.arg2 of the message and then feeds back to client,client the messages sent from the client to the server and the messages returned by the server are displayed.

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

Messenger of Android Process 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.