The Messenger class can pass Messge objects in different processes for data communication
Messenger is a lightweight IPC solution that encapsulates the aidl.
Steps:
1. Create the Messenger object in the service's Onbind () method, and associate the handler
PrivateHandler Mhandler =NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Casemsg_fromclient:log.i (TAG,"Received client information-------" +msg.getdata (). Get ("MSG"))); //get the Messenger object from the clientMessenger mmessenger=Msg.replyto; Message Mmessage=message.obtain (NULL, messengerservice.msg_fromclient); Bundle Mbundle=NewBundle (); Mbundle.putstring ("Rep", "Here's the server, we got the message."); Mmessage.setdata (Mbundle); Try{mmessenger.send (mmessage); } Catch(RemoteException e) {e.printstacktrace (); } Break; }}}; @Override Publicibinder onbind (Intent Intent) {return NewMessenger (Mhandler). Getbinder (); }}
Registering as a remote service android:process= in the manifest file ": Remotes
2. In the activity
Private New Handler () { @Override publicvoid handlemessage (Message msg) { Switch (msg.what) { case messengerservice.msg_fromclient: " Receive service-side information-------"+ msg.getdata (). Get (" rep ")) ; Break ; } } };
PrivateServiceconnection mserviceconnection=Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {
Create a Messenger object from a IBinder object Mmessenger=NewMessenger (service); Message Mmessage=message.obtain (NULL, messengerservice.msg_fromclient); Bundle Mbundle=NewBundle (); Mbundle.putstring ("MSG", "Here is the client, received the service side"); Mmessage.setdata (Mbundle); //deliver Messenger to the servermmessage.replyto=NewMessenger (Mhandler); Try{mmessenger.send (mmessage); } Catch(RemoteException e) {e.printstacktrace (); } }
IPC mechanism uses Messenger for interprocess communication