涉及類
Messenger
IMessenger
Handler
MessengerImpl使用場景
/**
* Reference to a Handler, which others can use to send messages to it.
* This allows for the implementation of message-based communication across
* processes, by creating a Messenger pointing to a Handler in one process,
* and handing that Messenger to another process.
*
* <p>Note: the implementation underneath is just a simple wrapper around
* a {@link Binder} that is used to perform the communication. This means
* semantically you should treat it as such: this class does not impact process
* lifecycle management (you must be using some higher-level component to tell
* the system that your process needs to continue running), the connection will
* break if your process goes away for any reason, etc.</p>
*/
簡而言之:跨進(jìn)程中用于 在一個進(jìn)程中發(fā)送消息,另一個進(jìn)程中的handler處理消息;
因此:
- Messenger需要綁定一個handler,另外可發(fā)送一個Message
- Messenger是Binder的一個簡單包裝
重要變量及方法:
private final IMessenger mTarget;
構(gòu)造函數(shù):
- 綁定handler,用于處理消息 --用于服務(wù)端
public Messenger(Handler target) {
mTarget = target.getIMessenger();
}
- 綁定IBinder, 用于跨進(jìn)程通信 --用于客戶端
public Messenger(IBinder target) {
mTarget = IMessenger.Stub.asInterface(target);
}
- 重要方法
其中這個用于跨進(jìn)程通信的binder怎么來的呢?
public IBinder getBinder() {
return mTarget.asBinder();
}
因此大概知道:兩個進(jìn)程間通過binder來通信; 某個進(jìn)程的Messenger綁定一個handler,這個handler是負(fù)責(zé)處理消息的; 同時提供一個此Messenger的binder, 另一個進(jìn)程新建Messenger時綁定這個binder,就可以發(fā)送消息了;(IMessenger對象)
-發(fā)送消息
public void send(Message message) throws RemoteException {
mTarget.send(message);
}
深入一點點:
其實Messenger 是對binder機(jī)制的一個簡單的封裝
何以見得呢:
我們注意到有個對象IMessager 以及它的方法send();
有沒有覺得這里面有什么貓膩?
- 由mTarget = target.getIMessenger();可以得到這個對象
那我們看下Handler的getIMessenger方法:
final IMessenger getIMessenger() {
synchronized (mQueue) {
if (mMessenger != null) {
return mMessenger;
}
mMessenger = new MessengerImpl();
return mMessenger;
}
}
繼續(xù)看MessengerImpl
private final class MessengerImpl extends IMessenger.Stub {
public void send(Message msg) {
msg.sendingUid = Binder.getCallingUid();
Handler.this.sendMessage(msg);
}
}
ok,基本明了了
其實IMessage就是 aidl跨進(jìn)程的一個定義數(shù)據(jù)交互的接口而已
而MessageImpl是它的具體實現(xiàn),里面的方法只有send()一個,也就是說它的場景簡單且粗暴: 跨進(jìn)程發(fā)送message,且是handler順序處理(串行)
- 簡單總結(jié)
- Messenger是AIDL的簡單封裝,適用于特定的場景
- 只有一個場景:發(fā)送消息; 方法只有send(Message)
- 內(nèi)部用handler處理,因此最后都是串行處理消息; 不適合大量并發(fā)的情況