Android Message源碼閱讀

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中用於排序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章