Android 消息機制之Message
@(Android)
Android的消息機制中,Message的使用是很頻繁的,處理消息,處理事件,處理其他我還沒有探索的新世界。在Android的消息機制中,Message相當于承載消息的載體,Handler就是Message的處理者,而MessageQueue和Looper就是Message的搬運工。
在Message的內部有一個flag的標志位,用于標識當前Message的狀態。有一個標志位是FLAG_IN_USE ,當Message在隊列中,正在給Handler處理的時候,就會加上這個標志位,表示當前的Message正在使用,那么為什么要記錄Message是否正在被使用呢。因為Message內部有一個對Message的回收機制。
因為Message作為Android系統消息的載體,那么若有大量消息需要處理的時候,就需要大量的Message,就需要不斷的new Message嗎,顯然這樣的很浪費時間的。所以Message內部弄了一個回收機制來管理Message。
Message的回收機制
和之前的文章一樣,既然是回收機制,那么自然會想到的問題就是,怎么回收,回收之后怎么利用?我們在學習Handler的時候 ,Google推薦我們使用Message的靜態方法obtain來得到一個新的Message實例。所以我們可以確定的是,回收之后的Message就是通過obtain來獲取新的Message的。那我們來看看obtain的源碼。
我們能看到的Message有很多obtain的重載,但是都使用了下面的無參方法,所以我們只看這份代碼就可以了
public static Message obtain() {
synchronized (sPoolSync) {
// sPool 就是Message的緩存池啦
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();
}
obtain方法不難,而且代碼很多,很容易理解吧。所以我們繼續尋找Message是在哪里被回收的。我找到了下面的兩個方法:
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
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的方法。在recycle()一開始就判斷了這個Message是否在使用,如果在使用就不回收啦。我之前一直以為Message的回收機制這些東西很高大上,其實在recycleUnchecked
里面只是對Message的所有成員變量清空,初始化一遍而已啊。最后緩沖池的大小再加一。
Message的其他東西
Message的源碼不是很多,所以我還看了別的代碼:
public void copyFrom(Message o) {
this.flags = o.flags & ~FLAGS_TO_CLEAR_ON_COPY_FROM;
this.what = o.what;
this.arg1 = o.arg1;
this.arg2 = o.arg2;
this.obj = o.obj;
this.replyTo = o.replyTo;
this.sendingUid = o.sendingUid;
if (o.data != null) {
this.data = (Bundle) o.data.clone();
} else {
this.data = null;
}
}
這個方法是復制一個Message,除了Mesasge的data數據之外,其他都是淺拷貝的。我覺得這個在平時的開發中可能會寫錯的,所有今天寫下來記錄一下
有一點我還是沒有想明白的,為什么Message要分同步和異步啊,有沒有dalao留個言說說什么回事啊