Messenger是对AIDL的封装,用于进程间通信,通过源码可以发现这点。
private final class MessengerImpl extends IMessenger.Stub {
public void send(Message msg) {
msg.sendingUid = Binder.getCallingUid();
Handler.this.sendMessage(msg);
}
}
服务端
public class MessengerService extends Service {
public static final String TAG = "MessengerService";
private final Messenger mMessenger = new Messenger(new MessengerHandler());
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private static class MessengerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constant.MESSAGE_FROM_CLIENT:
Log.d(TAG, "receive msg from client : " + msg.getData().getString("msg"));
break;
default:
super.handleMessage(msg);
}
}
}
}
客户端
//Messenger ----> Service
startService(Intent(this, MessengerService::class.java))
bindService(Intent(this, MessengerService::class.java), MyServiceConnect2(), 0)
private inner class MyServiceConnect2 : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
mMessenger = Messenger(service)
val message = Message.obtain().apply {
what = Constant.MESSAGE_FROM_CLIENT
data = Bundle().apply {
putString("msg", "hello,this is client")
}
}
try {
mMessenger.send(message)
Log.d(TAG, "onServiceConnected: send ${message.data.getString("msg")}")
} catch (e: RemoteException) {
e.printStackTrace()
}
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
AndroidManifest.xml定义
<service
android:name=".service.MessengerService"
android:exported="true"
android:process=":remote2" />
日志
2021-10-13 16:16:25.033 14318-14318/com.zjw.source D/MessengerService: receive msg from client : hello,this is client
走读源码
可以看到,就是继承IMessager.Stub,所以本质是封装了AIDL,方便于进程间通信。 其中只有一个send方法。
Handler中封装好了MessengerImpl,其getIMessenger方法如下,
final IMessenger getIMessenger() {
synchronized (mQueue) {
if (mMessenger != null) {
return mMessenger;
}
mMessenger = new MessengerImpl();
return mMessenger;
}
}
private final class MessengerImpl extends IMessenger.Stub {
public void send(Message msg) {
msg.sendingUid = Binder.getCallingUid();
Handler.this.sendMessage(msg);
}
}