Android 從源碼看Handler消息機制

今天閒的無聊,實在不知道幹嘛了,就想起來android中很重要的一個東西,消息機制,也就是我們常說的handler消息機制,下面我們就來一起看看;
1 實例化Handler


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

        }
    };

    我們來看看Handler裏面的handleMessage的方法說明,有這麼一句話:
    /**
     *子類必須實現,雖然不是抽象方法 
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

2 分發消息


    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

我們一般使用message只會給what和obj賦值,其實Message還有其他字段,如callBack,而mallback就Handler裏面的一個接口,只有在使用public Handler(Callback callback, boolean async) 重載方法的時候纔會給他賦值,所以這裏他是null,這樣就直接調用了Handler的handleMessage方法,講消息分發到了我們重寫的handleMessage方法再進行處理;

3 獲取msg

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();
    }

或者new Message()都可以;

4 發送消息


    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

源碼中消息最終在這裏加入消息隊列,而這個方法就是Handler裏面的方法,this指的就是Handler,可以看出,每一個Message都有一個標記。

5 消息隊列
如果在主線程中new Handler的話,系統或初始化一個,所以我們可以直接用:

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

如果在子線程:

public static void prepare() {
          prepare(true);
      }

    private static void prepare(boolean quitAllowed) {
          if (sThreadLocal.get() != null) {
              throw new RuntimeException("Only one Looper may be created per thread");
          }
          sThreadLocal.set(new Looper(quitAllowed));
     }

   private Looper(boolean quitAllowed) {
         mQueue = new MessageQueue(quitAllowed);
         mThread = Thread.currentThread();
     }

子線程要先prepare,可以看出其實最終都是調用的Looper這個方法;
發佈了65 篇原創文章 · 獲贊 9 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章