Handler的源碼講解

在Android中,Handler非常重要,在主線程的main方法中就使用了Handler,並且由於UI只能在UI線程上更新,Handler的使用更廣泛了,當然,Handler的使用不止是更新界面,例如:在子線程做一些耗時操作,完成後可能需要更新UI,不更新UI做一些其他事情也是可以的。

一般在多線程裏使用Handler都是通過下面的方式。

new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Handler mHandler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what){
                            case MESSAGE:
                                Log.d(TAG, "handleMessage: ");
                                break;
                        }

                    }
                };
                mHandler.sendEmptyMessage(MESSAGE);
                Looper.loop();
            }
        }).start();

但是由於我們在main線程經常用Handler,好多人可能會問,怎麼還有Looper?這是什麼鬼?
那麼接下來,我就從源碼的角度來解釋這個問題,順便梳理一下源碼。

源碼的理解

Handler mHandler = new Handler();這一步,我們進去看一看:
Handler類:

    public Handler() {
        this(null, false);
    }

    public Handler(Callback callback, boolean async) {
        ......
        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;
    }

上面構造方法中mLooper = Looper.myLooper();,接下來會有個判斷,那麼什麼時候mLooper == null?
進入Looper.myLooper();的源碼一探究竟,

    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

到這裏我們差不多是明白了些,原來Looper.myLooper()是得到該線程的Looper,而looper是存放在了ThreadLocal裏面,因此是從ThreadLocal裏面取出了Looper。但是ThreadLocal裏面會有looper嗎?我們把第一段代碼裏面的Looper.prepare();註釋掉運行一下試試看:
這裏寫圖片描述

拋出的異常正是if語句塊裏的代碼,而加上Looper.prepare();這行代碼後就沒有該異常出現了,那麼Looper.prepare()做了什麼呢?進去看一下:
Looper類中:

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

原來是向ThreadLocal中設置looper,設置之後new Handler()的時候也不會拋出異常了。
那麼接下來的問題又來了,Handler是怎麼發送消息的呢,又是怎麼樣才能取到消息處理掉?還是看源碼!

Handler發送消息

Handler類中:

    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 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);
    }
   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

上面的sendEmptyMessage、sendEmptyMessageDelayed和sendMessageDelayed都是我們經常用到的方法,最終都會走sendMessageAtTime方法。我們看一下這個方法,裏面有個MessageQueue,這又是什麼呢,這就是所謂的消息隊列,顧名思義,用來存放消息的。消息隊列的對象什麼時候創建的呢?
在Looper.prepare()中,會走sThreadLocal.set(new Looper(quitAllowed))這行代碼,我們看一看new Looper(quitAllowed)做了什麼?
Looper類:

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

原來消息隊列的對象是再Looper的構造方法中創建的,瞬間就明白了Looper.prepare()的重要性,不光是創建了Looper對象並放入了ThreadLocal,還創建了MessageQueue對象。在enqueueMessage中,有msg.target = this,這句代碼是把當前的Handler對象賦值給msg.target。接着看queue.enqueueMessage。這個是MessageQueue類中的方法:

    boolean enqueueMessage(Message msg, long when) {
        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;//當前待處理的消息
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {//將所有消息按照時間來排序
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

上述代碼是把消息插入到消息隊列當中,從上面代碼可以知道,消息隊列其實就是一個單鏈表。這個時候消息傳到了消息隊列,但是我們知道我們是再handler的handlerMessage中把消息處理掉了(不止這一種,還有通過post發送消息,在run方法中處理消息)。
在第一段代碼中,還有一行代碼沒有講到,我把源代碼貼出來看一下。
Looper類:

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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

通過代碼,我們看出首先得到當前線程的Looper對象,然後取出消息隊列(因爲消息隊列是在looper中創建的),接着進入了for語句塊,這是個無限循環,Message msg = queue.next()就很關鍵了,我們看一下

      Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                   continue;
                }
        }
    }

從上面代碼中可以看出來,這是從單鏈表中移除一個節點的操作,而節點就是消息,而且是在一個死循環裏面,如果消息隊列中沒有消息,就會在這裏發生阻塞。但是一旦有消息到來,就會把消息從消息隊列中移除。
那我們再回到Looper.looper()中。當取到的消息爲空的時候,就會退出for循環。如果取到了消息,那麼接下來會走msg.target.dispatchMessage(msg),而根據前面的講述msg.target就是當前的Handler對象,那麼dispatchMessage(msg)便是Handler中的方法,接着看源碼:
Handler類中:

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

上面方法是對消息進行分發,首先判斷msg.callback是否爲空,msg.callback是Runnable對象,這又是何方神聖,我們有時候還喜歡用post來發送消息,例如下:
同樣是在一個子線程中:

                Looper.prepare();
                Handler mHandler = new Handler();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                Looper.loop();

接着看post的源碼:

    public final boolean post(Runnable r){
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

    private static Message getPostMessage(Runnable r) {
       Message m = Message.obtain();
       m.callback = r;
       return m;
    }

哦!原來msg.callback就是post的Runnable對象,如果不爲空,說明採用了post的方式發送消息,那麼接下來應該執行run方法了,接着看handleCallback方法:

    private static void handleCallback(Message message) {
        message.callback.run();
    }

果不其然!!在這裏執行了run方法。
接着檢查mCallBack是不是爲空,,如果不爲空的話,會執行mCallback.handleMessage(msg)。對應的例子代碼:

                Looper.prepare();
                Handler mHandler = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        return false;
                    }
                });
                Looper.loop();

因爲Callback是個接口,handleMessage是接口中的方法,該方法在上面的例子中實現,那麼會執行實現的方法。
如果msg.callback和mCallBack都爲空的話,那麼就會執行handleMessage(msg),這是Handler中的方法:
Handler類:

    public void handleMessage(Message msg) {
    }

空的!!!我們在new Handler()的時候覆蓋了該方法,那麼就會走我們覆蓋後的方法。

結尾

終於寫完了,有的人可以很詫異,爲什麼在UI線程中不需要寫Looper.prepare()和Looper.loop()?
我湊!UI線程那麼重要,當然已經被創建好了,在Looper.prepareMainLooper()方法中一看便知。Looper.loop()在ui線程也已經準備好了,這裏就不帶着去看了。
又有問題來了,Android中爲什麼主線程不會因爲Looper.loop()裏的死循環卡死?
這裏有個很好的答案,附上鍊接如下:
答案鏈接

發佈了32 篇原創文章 · 獲贊 7 · 訪問量 4917
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章