Handler原始碼解析

許佳佳233發表於2017-06-21

#前提概要
Hanlder、Looper和MessageQueue算是android中的一大要點,關於其的解說也數不勝數,但他人的終究是他人的。
筆者自己從原始碼的角度對其深入瞭解一番,記錄成此篇文章。
#概述
**Looper:**每個執行緒只有一個Looper,它負責管理MessageQueue,會不斷的從MessageQueue中取出訊息,並將訊息分發給Handler處理。主執行緒在初始化的時候會建立一個Looper。
**MessageQueue:**用來存放Message的佇列,由Looper負責管理。
**Handler:**它能把訊息傳送給Looper管理的MessageQueue,並負責處理Looper分給它的訊息。

#Handler原始碼
##建構函式

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

主要操作如下:
1、獲取到當前的looper。
2、獲取到當前的MessageQueue
3、mCallback 是一個介面,其中包括一個回撥方法,可以進行message的攔截過濾,但是一般情況不用,為null。(後面會再提到)
4、mAsynchronous 表示執行的過程是非同步還是同步的。一般情況預設非同步。
##傳送Message到MessageQueue
Handler傳送Message的方法有多種,比較常見的有post(),sendMessage(),sendMessageDelayed(),sendEmptyMessage()等等,但是他們最終其實都會到enqueueMessage()這個方法,原始碼如下:

   public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, 0);
    }
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

msg.target而透過查詢Message原始碼我們也可以看到就是一個Handler,其中把this賦值給它。並且設定是非同步還是同步操作。
最終把msg放入了MessageQueue中。
##處理訊息
我們使用Handler時,都是透過定義handleMessage來實現訊息處理的,一般如下定義:

	   mHandler = new Handler() {
       public void handleMessage(Message msg) {
          // process incoming messages here
       }
   };

而當我們在Handler中看其原始碼時,卻發現它是一個空方法:

public void handleMessage(Message msg) {
}

所以我們其實只需要找到呼叫它的地方:

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

此處我們就看到了之前在建構函式中定義的mCallback,我們看到只有mCallback為null或者說mCallback.handleMessage()返回false的時候會執行我們定義的handleMessage()會執行。

當然,相信好奇的同學還是會去檢視以下mCallback的原始碼:

    final Callback mCallback;
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

於是我們發現其實它就是一個回撥函式,雖然其中的方法handleMessage()和Handler中的方法同名,但是兩者不是一個概念。

#Looper原始碼
##sThreadLocal變數

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

sThreadLocal是一個ThreadLocal類的例項,他負責儲存當先執行緒的Looper例項。

ThreadLocal:每個使用該變數的執行緒提供獨立的變數副本,每一個執行緒都可以獨立地改變自己的副本,而不會影響其它執行緒所對應的副本。ThreadLocal內部是透過map進行實現的;

##建構函式

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

Looper建構函式非常簡單,就是建立一個MessageQueue並且獲取到當前的執行緒。
##Looper.prepare()

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

此處首先去檢視sThreadLocal中是否有Looper例項,如果已經有的話,那麼就報異常,這是為了保證一個執行緒只有一個Looper存在。如果為空的話就建立Looper的例項。非常標準的單例模式。
##Looper.loop()

    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

程式碼比較長,但是邏輯比較簡單。
1、獲取到當前的Looper,如果為空就報異常,所以呼叫loop()之前首先要呼叫prepare()建立例項。
2、獲取到MessageQueue然後進入死迴圈遍歷,如果queue為空,那麼就跳出迴圈。
3、此處比較關鍵的程式碼如下:

		try {
                msg.target.dispatchMessage(msg);
            }

呼叫當前Message的Handler的dispatchMessage()方法。一般情況下也就是呼叫了我們在初始化Handler時定義的handleMessage()方法。

相關文章