Messenger是一种轻量级的IPC方案,它的底层实现其实就是AIDL.跨进程通信使用Messenger时,Messenger会将所有服务调用加入队列,然后服务端那边一次处理一个调用,不会存在同时调用的情况.而AIDL则可能是多个调用同时执行,必须处理多线程问
步骤详情
- 一、服务端
public class MyMessagerService extends Service {
@SuppressLint("HandlerLeak")
private Messenger messengerServices=new Messenger(new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 111://接收客户端发的消息
Log.e("TAG","获取客户端的name---"+msg.getData().getString("name"));//打印的数据:E/TAG: name---花花
Log.e("TAG","获取客户端的age---"+msg.getData().getInt("age",0));//打印的数据:E/TAG: age---2
Message message=new Message();
message.what=222;
Bundle bundle=new Bundle();
bundle.putString("ceshi","测试");
message.setData(bundle);
try {
msg.replyTo.send(message);//向客户端发消息
} catch (RemoteException e) {
throw new RuntimeException(e);
}
break;
}
}
});
@Nullable
@Override
public IBinder onBind(Intent intent) {
return messengerServices.getBinder();
}
}
Messager.replyTo
:指向的客户端的Messenger,而Messenger又持有客户端的一个IBinder对象(即MessengerImpl),服务端正是利用这个IBinder对象做的与客户端的通信。
- 注册服务
- 二、客户端
//给一个点击事件去绑定服务
public void btn6(View view) {
Intent intent = new Intent();
intent.setAction("com.example.jinc2application.MyMessagerService");
intent.setPackage("com.example.jinc2application");//包名
bindService(intent, myMeaaengerConnection, Service.BIND_AUTO_CREATE);
}
private Messenger messenger;
private ServiceConnection myMeaaengerConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messenger=new Messenger(iBinder);
Message message=new Message();
message.what=111;
Bundle bundle=new Bundle();
bundle.putString("name","花花");
bundle.putInt("age",2);
message.setData(bundle);
message.replyTo=mMessengerHandler;
try {
messenger.send(message);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@SuppressLint("HandlerLeak")
private Messenger mMessengerHandler=new Messenger(new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 222:
Log.e("TAG","获取服务端的数据---"+msg.getData().getString("ceshi"));//打印的数据:E/TAG:---测试
break;
}
}
});