码迷,mamicode.com
首页 > 系统相关 > 详细

IPC机制 用Messenger进行进程间通信

时间:2016-04-15 15:30:10      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

Messenger类可以在不同进程中传递Messge对象进行数据通信

Messenger是轻量级的IPC方案对AIDL进行了封装。

步骤:

1、在Service的onBind()方法中创建Messenger对象,并关联Handler

 private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FROMCLIENT:
                    Log.i(TAG,"收到客户端信息-------"+msg.getData().get("msg"));
                    //得到客户端传来的Messenger对象
                    Messenger mMessenger=msg.replyTo;
                    Message mMessage=Message.obtain(null,MessengerService.MSG_FROMCLIENT);
                    Bundle mBundle=new Bundle();
                    mBundle.putString("rep","这里是服务端,我们收到信息了");
                    mMessage.setData(mBundle);
                    try {
                        mMessenger.send(mMessage);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
@Override
    public IBinder onBind(Intent intent) {

        return new Messenger(mHandler).getBinder();
    }
}
//在清单文件中 注册为 远程Service android:process=":remote

2.在Activity中

private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MessengerService.MSG_FROMCLIENT:
                    Log.i(MessengerService.TAG, "收到服务端信息-------" + msg.getData().get("rep"));
                    break;
            }
        }
    };


private ServiceConnection mServiceConnection=new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
      //通过 IBinder 对象 创建 Messenger对象 mMessenger
=new Messenger(service); Message mMessage=Message.obtain(null,MessengerService.MSG_FROMCLIENT); Bundle mBundle=new Bundle(); mBundle.putString("msg", "这里是客户端,收到了嘛服务端"); mMessage.setData(mBundle); //将Messenger传递给服务端 mMessage.replyTo=new Messenger(mHandler); try { mMessenger.send(mMessage); } catch (RemoteException e) { e.printStackTrace(); } }

 

 

IPC机制 用Messenger进行进程间通信

标签:

原文地址:http://www.cnblogs.com/pbq-dream/p/5395544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!