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(); } }
时间: 2024-10-12 18:44:39