We use handler in a process, how do we use handler across processes?
In fact, this problem is not difficult to solve, self-made to the binder for some encapsulation can be easily implemented. But when you look at the system source code, you will find that, in fact, these Android have been done for us.
using the Android system Android.os.Messenger It is convenient to use handler across processes. The following is an example program.
The first is the service side.
public class messengertestservice extends service { protected static final string tag = "Messengertestservice"; private handler mhandler = new handler () { @Override Public void handlemessage (message msg) { switch (msg.what) { case 1:    LOG.D (tag, "received message"); //get Messenger in client message for callback final messenger callback = msg.replyto; try { // Callback callback.send (Message.obtain (null, 0)); } catch (remoteexception e) { // todo Auto-generated catch block e.printstacktrace (); } break; } } }; @Override public ibinder onbind (intent intent) { return new messenger (MHandler). GetBinder (); } }
Then the client
public class mainactivity extends activity { protected static final String TAG = "Mainactivity"; messenger messenger; Messenger reply; @Override protected void oncreate (bundle savedinstancestate) { super.oncreate (savedinstancestate); setcontentview (R.layout.activity_main); reply = new messenger (handler); intent intent = new intent (); intent.setclassname ("Test.messenger", "Test.messenger.MessengerTestService"); // Binding Service bindservice (intent, new serviceconnection () { @Override public void onservicedisconnected ( Componentname name) { } @Override public void onserviceconnected (Componentname name, ibinder service) { &Nbsp; toast.maketext (mainactivity.this, "bind success ", 0). Show (); messenger = new messenger (Service); } }, context.bind_auto_create); } public void sendmessage (VIEW V) { Message Msg = message.obtain (null, 1); // Sets the messenger msg.replyto = reply; of the call back try { messenger.send (msg); } catch (remoteexception e) { e.printstacktrace (); } } private handler handler = new handler () { @Override public void handlemessage ( message msg) { log.d (TAG, "Callback succeeded"); } };}
The client binds the server side, obtaining the Binder object for remote Messenger. Call Messenger's send function, and you can send the message to the handler on the server.
At the same time, if you need a server callback client (handler to the client), you can set the ReplyTo in the Send message, and the server can send messages to the client.
Below we look at the source of Messenger, or is very simple.
constructor function
Public Messenger (Handler target) {mtarget = Target.getimessenger (); }
Handler.getimessenger () returns a IMessenger binder object whose send method will invoke the SendMessage method of Handler.
public void Send (Message message) throws RemoteException {mtarget.send (message); }
Use of Messenger in Android