Using Messenger for inter-process communication between Android

Source: Internet
Author: User

Messenger, Messenger, can use it for interprocess communication, and Messenger requests the Service in a queue, so it does not support multithreaded communication.

Check out the official documentation for Messenger 's explanation:

Reference to a Handler, which others can with send messages to it. This allows for the implementation of

message-based communication across processes, by creating a Messenger pointing to a Handler in one process,

and handing that Messenger to another process.

The client and the server can hold each other's messenger to communicate, let's look at the specific implementation.

Create two projects under Eclipse, for both client and server:

Client-side implementation, create messenger for the client, and use Messenger's construction method to point to a handler instance, which is used to process the messages sent by the service side.

While the client obtains the server Messenger via onserviceconnected, using this Messenger to send a message to the server, the messenger of the client is passed to the server through the ReplyTo of the message.

1  Public classMainactivityextendsActivity {2 3     Private Static FinalString TAG = "--debug--";4 5     //action to start the service6     Private Static FinalString start_server_action = "Com.young.server.START_SERVICE";7     Private Static Final intWhat_on_to_service = 1;8     Private Static Final intWhat_on_to_client = 2;9 Ten     PrivateButton mbindbtn; One     Private BooleanIsbindservice =false; A  - @Override -     protected voidonCreate (Bundle savedinstancestate) { the         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -MBINDBTN =(Button) Findviewbyid (r.id.bind_service); -Mbindbtn.setonclicklistener (NewOnclicklistener () { + @Override -              Public voidOnClick (View v) { +Bindservice (NewIntent (start_server_action), Conn, context.bind_auto_create); A             } at         }); -     } -  -     //client side handler for handling messages sent from the server side -     PrivateHandler Mclienthandler =NewHandler (NewCallback () { - @Override in          Public Booleanhandlemessage (Message msg) { -             Switch(msg.what) { to              Casewhat_on_to_client: +LOG.V (TAG, "the client receives a message from the server! "); -                  Break; the  *             default: $                  Break;Panax Notoginseng             } -             return false; the         } +     }); A  the     //client-side Messenger +     PrivateMessenger Mclientmessenger =NewMessenger (mclienthandler); -  $     PrivateServiceconnection conn =Newserviceconnection () { $  - @Override -          Public voidonservicedisconnected (componentname name) { theLOG.V (TAG, "service Disconnected"); - WuyiIsbindservice =false; theMclientmessenger =NULL; -         } Wu  - @Override About          Public voidonserviceconnected (componentname name, IBinder service) { $LOG.V (TAG, "service is linked"); -  -Isbindservice =true; -             //get the server-side Messenger Messenger instance AMessenger Servermessenger =NewMessenger (service); +             //messages sent to the server side theMessage toservermessage = Message.obtain (NULL, what_on_to_service); -             //passing the client's messenger to the service via ReplyTo $Toservermessage.replyto =Mclientmessenger; the             Try { the servermessenger.send (toservermessage); the}Catch(RemoteException e) { the e.printstacktrace (); -             } in         } the     }; the  About     protected voidOnStop () { the         if(Isbindservice) the Unbindservice (conn); the         Super. OnStop (); +     }; -}

The implementation of service-side services, after the server received the client's message, through the ReplyTo of the message to remove the client Messenger, using this Messenger to send messages to the client, which enables two-way communication between processes.

The service side uses Messenger's Getbinder method to return the IBinder object to the client for sharing messenger on the server side.

1  Public classRemoteserviceextendsService {2     Private Static FinalString TAG = "--debug--";3 4     Private Static Final intWhat_on_to_service = 1;5     Private Static Final intWhat_on_to_client = 2;6 7     //server-side handler, used to process messages sent by the client8     PrivateHandler Mserverhandler =NewHandler (NewCallback () {9 @OverrideTen          Public Booleanhandlemessage (Message msg) { One             Switch(msg.what) { A              CaseWhat_on_to_service: -LOG.V (TAG, "message received from client"); -                 //server-side get Messenger messenger on client side theMessenger Clientmessenger =Msg.replyto; -Message toclientmsg = Message.obtain (NULL, what_on_to_client); -                 Try { -                     //sending messages to clients using client Messenger + clientmessenger.send (toclientmsg); -}Catch(RemoteException e) { + e.printstacktrace (); A                 } at                  Break; -  -             default: -                  Break; -             } -             return false; in         } -     }); to  +     //server-side Messenger Messenger -     PrivateMessenger Mservermessenger =NewMessenger (mserverhandler); the  * @Override $      Publicibinder onbind (Intent Intent) {Panax Notoginseng         returnMservermessenger.getbinder (); -}

Then take a look at the claims of the Server service, because to start the service in another process, set android:exported to True, and also start permissions for service join.

1 <permission android:protectionlevel= "normal" android:name= "Young.permission.START_SERVICE" ></ Permission> 2      3 <service  4     android:name= " Com.young.server.RemoteService " 5     android:permission=" Young.permission.START_SERVICE " 6     android:exported= "true" > 7     <intent-filter> 8         <action android: Name= "Com.young.server.START_SERVICE"/> 9     </intent-filter> </service >

Finally, you add the appropriate startup service permissions on the client.

<uses-permission android:name= "Young.permission.START_SERVICE"/>

After the program runs, you can see that both the client and the server receive messages from each other.

11-12 12:58:37.197:v/--debug--(21322): service is linked
11-12 12:58:37.197:v/--debug--(21268): Received a message from the client
11-12 12:58:37.197:v/--debug--(21322): The client receives a message from the service side!

Using Messenger for inter-process communication between Android

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.