Android笔记之Messenger

Messenger是Android中跨进程通信的一种方式,是对AIDL的简化封装版,使用简单方便,相对透明,不用考虑脚本的生成的问题。

Messenger的使用

双端各持有一个Messenger,只需要在各自的Handler中捕获(handleMessage)自己关心的 消息即可
客户端通过ServiceConnection绑定服务端

服务端:

 @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();//返回消息所属的Binder
    }
    private Messenger mMessenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case MSG_TARGET:
                    Message replay = Message.obtain(msg);
                    replay.what = MSG_TARGET;
                    try {
                        msg.replyTo.send(replay);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    });

客户端:

    private Messenger mServerService;
    private Messenger mMessenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case MSG_TARGET:
                    //处理
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    });
     private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(final ComponentName name, final IBinder service) {
            if (service != null) {
                mServerService = new Messenger(service);
                Message msg = Message.obtain();
                msg.what = MSG_TARGET;
                msg.replyTo = mMessenger;
                try {
                    mServerService.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(final ComponentName name) {
            mServerService = null;
        }
    };

IMessenger的原型(adil)

package android.os;  
import android.os.Message;  
/** @hide */  
oneway interface IMessenger {  
    void send(in Message msg);  
} 

参考:
http://blog.csdn.net/lmj623565791/article/details/47017485

你可能感兴趣的:(Android笔记之Messenger)