Android Framework源碼分析----Handler、Message、MessageQueue、Looper

Message:線程間通訊的消息體

Handler: 主要是負(fù)責(zé)發(fā)送消息,和接收消息

MessageQueue:負(fù)責(zé)以隊(duì)列的方式存儲(chǔ)消息

Looper: 就是一直輪詢的從MessageQueue中取消息,獲取到消息就通過(guò)dispatchMessage()將消息發(fā)送給Handler去處理。

舉例理解一下:

平常生活中,從網(wǎng)上購(gòu)物,商家把一個(gè)商品打包好后,將郵件投遞給了快遞公司,快遞公司就從投遞的網(wǎng)點(diǎn)取出來(lái)郵件,然后根據(jù)郵件上的地址將郵件發(fā)送給收件人,那么這里的郵件就是Message , 而快遞公司的收寄網(wǎng)點(diǎn)就像是MessageQueue ,然后快遞公司取到郵件后按照地址發(fā)送郵件,就類似Looper , 最后收件人接收快遞。

這樣理解,就可以明白這其實(shí)就是一種生產(chǎn)者消費(fèi)者的模式。

Handler原理.png

一、Message消息

1、Message創(chuàng)建

下面三種獲取消息的方式基本上類似:

從全局池中獲取新的消息實(shí)例,這樣就可以達(dá)到復(fù)用用過(guò)的消息,避免創(chuàng)建銷毀消息對(duì)象,這樣性能和內(nèi)存上都比直接new一個(gè)消息要好。

//Message.java
    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    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();
    }

    /**
     * Same as {@link #obtain()}, but copies the values of an existing
     * message (including its target) into the new one.
     * @param orig Original message to copy.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Message orig) {
        Message m = obtain();
        m.what = orig.what;
        m.arg1 = orig.arg1;
        m.arg2 = orig.arg2;
        m.obj = orig.obj;
        m.replyTo = orig.replyTo;
        m.sendingUid = orig.sendingUid;
        m.workSourceUid = orig.workSourceUid;
        if (orig.data != null) {
            m.data = new Bundle(orig.data);
        }
        m.target = orig.target;
        m.callback = orig.callback;

        return m;
    }

    /**
     * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
     * @param h  Handler to assign to the returned Message object's <em>target</em> member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;

        return m;
    }


//這里也可以給message設(shè)置一個(gè)處理message的callback ,在Handler處理消息的時(shí)候使用
    public static Message obtain(Handler h, Runnable callback) {
        Message m = obtain();
        m.target = h;
        m.callback = callback;

        return m;
    }

二、Handler消息發(fā)送與消費(fèi)流程

1、發(fā)送消息

//Handler.java
   public final boolean sendMessage(@NonNull Message msg) {
       //注意這里傳入的第二個(gè)參數(shù)delayMillis  為 0 
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        //繼續(xù)進(jìn)入sendMessageAtTime()
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

   public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
       //這里為什么要講成員變量mQueue賦值給一個(gè)局部變量呢?筆者猜想這樣如果出現(xiàn)對(duì)mQueue的多線程操作,就不會(huì)導(dǎo)致阻塞;
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
       //這里傳入enqueueMessage的第三個(gè)參數(shù)不在是0 ,已經(jīng)修改了的
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;//這里的this就是當(dāng)前的Handler,這樣msg就和當(dāng)前的Handler綁定在一起了
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        
        //這里就會(huì)進(jìn)入到MessageQueue的enqueueMessage()方法中去
        return queue.enqueueMessage(msg, uptimeMillis);
    }

至此,Handler通過(guò)sendMessage 一步一步將msg 加入到MessageQueue中,這樣就完成了消息的發(fā)送。

2、消費(fèi)消息

根據(jù)上面的Handler運(yùn)行機(jī)制我們可以知道,從消息隊(duì)列獲取消息是在Looper的loop中通過(guò)一個(gè)無(wú)限循環(huán)來(lái)完成,然后通過(guò)獲取到的消息target(也就是在發(fā)送消息時(shí)傳入的Handler)來(lái)講消息dispatchMessage()分發(fā)出去。關(guān)于Looper中獲取消息會(huì)在第四部分分析,這里就只從Handler的dispatchMessage()開(kāi)始。

//Handler.java
/**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            //1)處理消息1:如果在msg中設(shè)置了callback ,那么就會(huì)從這里進(jìn)行消息的處理
            handleCallback(msg);
        } else {
            //2)處理消息2:這里的mCallback是一個(gè)接口類型,也就說(shuō)需要將該接口的實(shí)例對(duì)象傳遞進(jìn)來(lái)就會(huì)走這里的分支,調(diào)用其handleMessage()方法
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //3)處理消息1:重寫handleMessage
            handleMessage(msg);
        }
    }

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

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(@NonNull Message msg) {
    }
    

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

//1. 消息創(chuàng)建時(shí)傳入callback ,就會(huì)使用消息自帶的callback來(lái)處理消息
    public static Message obtain(Handler h, Runnable callback) {
        Message m = obtain();
        m.target = h;
        m.callback = callback;

        return m;
    }

//2. 給Handler設(shè)置callback
    public Handler(@Nullable 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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

消費(fèi)消息有三種方式:

  1. 在創(chuàng)建Message設(shè)置自己的callback
  2. 在創(chuàng)建Handler消息是,給Handler對(duì)象設(shè)置callback(注意這類構(gòu)造是hide)
  3. 重寫Handler的handleMessage()方法(這種也是最常見(jiàn)的)

Handler的工作流程:

Handler通過(guò)發(fā)送一個(gè)消息,將消息加入到消息隊(duì)列中,然后Looper從消息隊(duì)列中取出消息后通過(guò)Handler的dispatchMessage()將消息分發(fā)出去,消息的處理可以有Message自帶的callback 、handler的callback 或者重寫的handler的handleMessage()來(lái)完成消息的消費(fèi)。

三、MessageQueue分析

MessageQueue作為一個(gè)存儲(chǔ)消息的隊(duì)列容器,那么他的核心就是消息的存儲(chǔ)和取出。

1、消息入隊(duì)(enqueueMessage)

  1. 在入隊(duì)時(shí)使用了Synchronized鎖,鎖的是this,也就是說(shuō)對(duì)同一個(gè)MessageQueue對(duì)象的所有調(diào)用者來(lái)說(shuō),都是互斥的,他們必須等到上一個(gè)調(diào)用者釋放了鎖,后面調(diào)用者才能執(zhí)行鎖中的代碼;
  2. 在消息加入隊(duì)列的時(shí)候,會(huì)按照消息執(zhí)行的時(shí)間順序進(jìn)行隊(duì)列的排序;
//MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

    //這里的synchronized鎖需要注意一下
        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

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

2、消息出隊(duì)(next)

消息出隊(duì)主要就是將隊(duì)列的首部取出,因?yàn)樵谌腙?duì)的時(shí)候已經(jīng)按照時(shí)間進(jìn)行了排序;

在取消息時(shí)也使用了synchronized鎖,這個(gè)鎖是用來(lái)針對(duì)調(diào)用者enqueueMessage、next只能執(zhí)行一個(gè)操作,不能同時(shí)進(jìn)行,這樣就可以保證消息的不同線程訪問(wèn)的時(shí)候有序的進(jìn)行。

//MessageQueue.java
 Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

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

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }//這里就synchronized就結(jié)束了

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

3、同步屏障

根據(jù)上面的內(nèi)容,消息的發(fā)送是同步的(即按照排隊(duì)順序一條一條執(zhí)行),如果有一條緊急的消息需要處理時(shí),按照常規(guī)就需要繼續(xù)排隊(duì),等到滿足了自己執(zhí)行的條件再處理該消息,那么這時(shí)候同步屏障就來(lái)了,同步屏障說(shuō)白了就是開(kāi)通的消息的綠色通道。

例如:在高速上遇到堵車的情況,常規(guī)就應(yīng)該排隊(duì)等待,高速的應(yīng)急車道就可以理解成是同步屏障,這樣可以處理一些緊急的事情。

3.3.1 設(shè)置同步屏障:

//MessageQueue.java
    public int postSyncBarrier() {
        return postSyncBarrier(SystemClock.uptimeMillis());
    }

//注意下下面并沒(méi)有給msg設(shè)置target
private int postSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;

            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }

3.3.2 Looper取消息時(shí)處理同步屏障

  1. 由于在設(shè)置同步屏障時(shí)并沒(méi)有給msg設(shè)置target ,所有就會(huì)進(jìn)入下面的do while里;
  2. while的條件(isAsynchronous 默認(rèn)是false ,msg 也不為Null),所以會(huì)循環(huán)執(zhí)行
  3. msg 每一次循環(huán)都會(huì)獲取下一條消息,也就是會(huì)變量消息隊(duì)列中的所有消息執(zhí)行;
  4. 屏障在執(zhí)行,下面的同步代碼塊就不會(huì)執(zhí)行,需要等待;
  5. 需要溢出同步屏障后方可執(zhí)行后面的同步代碼塊;
//MessageQueue.java
 Message next() {   
        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) {
                    // 這里就是處理同步屏障消息的
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
              //.......此處省略了很多代碼 
            }
        }
    }

//移除同步屏障
 public void removeSyncBarrier(int token) {
        // Remove a sync barrier token from the queue.
        // If the queue is no longer stalled by a barrier then wake it.
        synchronized (this) {
            Message prev = null;
            Message p = mMessages;
            while (p != null && (p.target != null || p.arg1 != token)) {
                prev = p;
                p = p.next;
            }
            if (p == null) {
                throw new IllegalStateException("The specified message queue synchronization "
                        + " barrier token has not been posted or has already been removed.");
            }
            final boolean needWake;
            if (prev != null) {
                prev.next = p.next;
                needWake = false;
            } else {
                mMessages = p.next;
                needWake = mMessages == null || mMessages.target != null;
            }
            p.recycleUnchecked();

            // If the loop is quitting then it is already awake.
            // We can assume mPtr != 0 when mQuitting is false.
            if (needWake && !mQuitting) {
                nativeWake(mPtr);
            }
        }
    }

四、Looper 分析

1、Looper的創(chuàng)建

  1. 創(chuàng)建Looper時(shí),給mQueue構(gòu)造方法傳入了是否允許退出的值為true ,是因?yàn)镸essage的quit()方法,如果傳入的是false ,那么調(diào)用quit()會(huì)拋出 ' Main thread not allowed to quit. ' 的異常
  2. 創(chuàng)建主線程Looper其實(shí)和prepare基本上是一致的,只是傳入的quitAllowed的值為false
//Looper.java
public static void prepare() {
        //這里默認(rèn)傳入的是否允許退出為:true
     prepare(true);
}

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
       throw new RuntimeException("Only one Looper may be created per thread");
    }
    //這里進(jìn)入Looper的構(gòu)造函數(shù),構(gòu)造的參數(shù)傳入的是false
    //把創(chuàng)建好的Looper對(duì)象加入到ThreadLocal中
    sThreadLocal.set(new Looper(quitAllowed));
}

private Looper(boolean quitAllowed) {
    //這里創(chuàng)建了一個(gè)消息隊(duì)列
     mQueue = new MessageQueue(quitAllowed);
    //獲取當(dāng)前線程
     mThread = Thread.currentThread();
}

//》》》》》》》》》》》》》》》》》》》》》》》》》》》》
//準(zhǔn)備一個(gè)主線程Looper
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

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

2、Looper開(kāi)始工作

  1. 獲取創(chuàng)建好的Looper對(duì)象
  2. 從Looper對(duì)象中獲取消息隊(duì)列
  3. 通過(guò)一個(gè)死循環(huán)從消息隊(duì)列中去消息,如果消息隊(duì)列中有消息,就調(diào)用消息體中的Target進(jìn)行DispatchMessage()
//Looper.java
 public static void loop() {
        //這里取出來(lái)之前創(chuàng)建好的Looper對(duì)象
        final Looper me = myLooper();
        if (me == null) {
            //如果沒(méi)有Looper對(duì)象,就會(huì)拋出需要調(diào)用prepare()的異常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
  
        final MessageQueue queue = me.mQueue;
        for (;;) {
            //這里是一個(gè)死循環(huán),從消息隊(duì)列中取消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                return;
            }

            try {
                //這里通過(guò)消息體中的target調(diào)用dispatchMessage()來(lái)分發(fā)消息
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
            }
        }
    }

3、Looper結(jié)束工作

//Looper.java
   public void quit() {
        mQueue.quit(false);
    }


   public void quitSafely() {
        mQueue.quit(true);
    }

總結(jié):

一個(gè)線程對(duì)應(yīng)一個(gè)Looper, 一個(gè)Looper包含一個(gè)MessageQueue,這樣多個(gè)Handler在發(fā)送消息時(shí),通過(guò)MessageQueue中的同步鎖來(lái)達(dá)到線程同步的目的,消息隊(duì)列采用鏈表的結(jié)構(gòu)來(lái)對(duì)消息進(jìn)行排序,Looper通過(guò)一個(gè)無(wú)限循環(huán)從消息隊(duì)列中取消息。然后再通過(guò)Message的Target進(jìn)行dispatchMessage,然后進(jìn)入Handler的hanleMessage()處理消息。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容