Message是作为Messenger或者MessageQueue中的信息载体,故此阅读分析一下其代码
1.实现的接口
Message实现了Parcelable接口,以使其在能够在进程间传递。
2.字段
主要字段是
- what
用于标识信息内容 - arg1,arg2
可以消耗很低的携带整形数据 - replyTo
可携带返回数据的Messenger - sendingUid
指示发送消息的uid的可选字段。并且只在被Messenger发送时有效,否则只会获得-1 - next
Message next字段说明Message是一个链表
3.函数
- obtain函数
private static Message sPool;
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
可以看出该Message是一个单例
- recycle函数
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
recycle函数负责message的回收检查,判断改message是否在使用,若在使用则返回,否则调用recycleUnchecked();
- recycleUnchecked
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
该函数对message进行数据清除,维护Message链表
-
copyFrom
Message 拷贝函数 -
getWhen
获取long when字段,在MessageQueue中用于排序