转载:http://glason.diandian.com/post/2011-09-03/4653170
Using a Messenger
Compared to AIDL
When you need to perform IPC, using a Messenger for your interface is simpler than implementing it with AIDL, because Messenger queues all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the service, which must then handle multi-threading.
For most applications, the service doesn't need to perform multi-threading, so using a Messenger allows the service to handle one call at a time. If it's important that your service be multi-threaded, then you should use AIDL to define your interface.
If you need your service to communicate with remote processes, then you can use a Messenger to provide the interface for your service. This technique allows you to perform interprocess communication (IPC) without the need to use AIDL.
Here's a summary of how to use a Messenger:
- The service implements a Handler that receives a callback for each call from a client.
- The Handler is used to create a Messenger object (which is a reference to the Handler).
- The Messenger creates an IBinder that the service returns to clients from onBind().
- Clients use the IBinder to instantiate the Messenger (that references the service's Handler), which the client uses to send Message objects to the service.
- The service receives each Message in its Handler—specifically, in the handleMessage() method.
In this way, there are no "methods" for the client to call on the service. Instead, the client delivers "messages" (Message objects) that the service receives in its Handler.
Here's a simple example service that uses a Messenger interface:
public class MessengerService extends Service {
/** Command to the service to display a message */
static final int MSG_SAY_HELLO = 1 ;
/**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage ( Message msg ) {
switch ( msg . what ) {
case MSG_SAY_HELLO :
Toast . makeText ( getApplicationContext (), "hello!" , Toast . LENGTH_SHORT ). show ();
break ;
default :
super . handleMessage ( msg );
}
}
}
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger ( new IncomingHandler ());
/**
* When binding to the service, we return an interface to our messenger
* for sending messages to the service.
*/
@Override
public IBinder onBind ( Intent intent ) {
Toast . makeText ( getApplicationContext (), "binding" , Toast . LENGTH_SHORT ). show ();
return mMessenger . getBinder ();
}
}