Messager与AIDL比较(转)


转载: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:

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 (); 
    } 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值