Android 線程間通信Looper和Handler(1) -- Java層

在Android 系統(tǒng)中通常都說有四大組件:Activity,Service,Broadcast和Content Provider,但是還有兩個最重要的東西是支撐整個Android 系統(tǒng)的進程間通信和線程間通信:Binder和消息隊列。

Binder,是Android 系統(tǒng)使用的進程間通信,不論是應(yīng)用層Java代碼編寫的進程還是C/C++編寫的native進程都是通過Binder進行進程間通信的,Binder通信的實現(xiàn)也是很復(fù)雜,牽扯到驅(qū)動,runtime,native和Java Service,最基本的實現(xiàn)是通過進程間的共享內(nèi)存來實現(xiàn)的,我們這次不討論Binder。

消息隊列,主要負責整個Android系統(tǒng)中消息的處理和分發(fā),比如整個Android 系統(tǒng)InputManagerService就是依賴于Handler機制實現(xiàn)的,以及不同線程間通信的橋梁。

重要的幾個類

  • Looper: 不斷循環(huán)執(zhí)行(Looper.loop), 按分發(fā)機制將消息分發(fā)給目標處理者

  • Handler: 消息輔助類,主要功能是向消息池發(fā)送各種消息事件(Handler.sendMessage)和處理相應(yīng)的消息事件(Handle.handleMessage)

  • MessageQueue: 消息隊列的主要功能是向消息池投遞消息(MessageQueue.enqueueMessage)和取走消息池的消息(MessageQueue.next)

  • Message: 消息分為硬件產(chǎn)生的消息(如按鈕,觸摸)和軟件生產(chǎn)的消息

這幾個類在源代碼的位置:

framework/base/core/java/andorid/os/
- Handler.java
- Looper.java
- Message.java
- MessageQueue.java

類的框架圖:


Android MessageQueue.png
  • Looper有一個MessageQueue消息隊列

  • MessageQueue有一組待處理的Message

  • Message中有一個用于消息處理的Handler

  • Handler中有Looper和MessageQueue

Handler線程間通信實例

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

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

        Looper.loop();
    }
}

可以看到LooperThread是一個子線程,在這個線程的run方法中有實現(xiàn)了Handler的handleMessage方法,這個方法就是用來接收消息然后做相應(yīng)的處理,主線程就可以通過LooperThreadmHandler來發(fā)送消息到子線程中,從而實現(xiàn)線程間通信。

下面就圍繞著這段代碼來解析一下源代碼

Looper

Looper.prepare()

代碼里面直接調(diào)用的是Looper.prepare(),默認調(diào)用的是prepare(true),標識的是這個Looper允許退出,false則表示不允許退出。

// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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));
}

這里的sThreadLocal是ThreadLocal類型。

ThreadLocal: 線程本地存儲區(qū)(Thread Local Storage, 簡稱為TLS),每個線程都有自己的私有本地存儲區(qū)域,不同線程之間彼此不能訪問對方的TLS區(qū)域。

ThreadLocal的get()set()方法操作的類型都是泛型,

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

可見sThreadLocal通過get和set的是Looper類型。

Looper.prepare()在每個線程中只允許執(zhí)行一次,該方法會創(chuàng)建Looper對象,Looper的構(gòu)造方法中會創(chuàng)建一個MessageQueue對象,再通過Looper對象保存到當前線程的TLS。

Looper構(gòu)造方法

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);     //創(chuàng)建MessageQueue對象
    mThread = Thread.currentThread();           //記錄當前線程
}

Looper.loop()

public static void loop() {
    final Looper me = myLooper();           //從TLS中獲取當前Looper對象
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;   //獲取Looper對象中的消息隊列

    // 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();
    //確保在權(quán)限檢查時基于本地進程,而不是調(diào)用進程
    final long ident = Binder.clearCallingIdentity();

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
        SystemProperties.getInt("log.looper."
                                + Process.myUid() + "."
                                + Thread.currentThread().getName()
                                + ".slow", 0);

    boolean slowDeliveryDetected = false;

    for (;;) {          //進入loop的主循環(huán)
        Message msg = queue.next(); //可能會阻塞,取決于消息池中有無可用消息
        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;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        try {
            //用于給target分發(fā)消息使用
            msg.target.dispatchMessage(msg);
            //記錄分發(fā)消息用了多長時間
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                                msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
        }

        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.
        // 恢復(fù)調(diào)用者信息
        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);
        }
        //講Message放入到消息池來循環(huán)利用
        msg.recycleUnchecked();
    }
}

loop()進入循環(huán),不斷的重復(fù)下面的操作,知道MessageQueue.next()方法返回的是null

  • 讀取MessageQueue的下一條Message

  • 把Message分發(fā)給相應(yīng)的target

  • 再把分發(fā)后的Message回收到消息池,以便重復(fù)利用

消息處理的核心部分就干這么幾件事情,

Looper.quit()

public void quit() {
    mQueue.quit(false);
}

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

最終是調(diào)用到MessageQueue.quit()方法

void quit(boolean safe) {
    //當mQuitAllowed為false,標識不允許退出,調(diào)用quit會拋出異常
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            //移除尚未觸發(fā)的所有消息
            removeAllFutureMessagesLocked();
        } else {
            //移除所有的消息
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

消息退出的方式有兩種:

  • safe=true時,只移除上位觸發(fā)的所有消息,對于正在觸發(fā)的消息不移除

  • safe=false時,移除所有的消息

Looper.myLooper

用于偶去TLS存儲的Looper對象

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

Handler

構(gòu)造Handler

無參構(gòu)造

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

public Handler(Callback callback, boolean async) {
    //匿名類、內(nèi)部類或本地類都必須申明為static,否則會警告可能出現(xiàn)的內(nèi)存泄漏
    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());
        }
    }
    //必須先執(zhí)行Looper.prepare(),才能獲取Looper對象,否則為null
    mLooper = Looper.myLooper();    //從當前線程的TLS中獲取Looper對象
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
            + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;    //消息隊列,來自Looper對象
    mCallback = callback;       //回調(diào)方法
    mAsynchronous = async;      //設(shè)置消息是否為異步處理方式
}

對于Handler的無參構(gòu)造方法,默認采用當前線程TLS中的Looper對象,并且callback回調(diào)方法為null,且消息為同步處理方式。只要執(zhí)行的Looper.prepare()方法,那么便可以獲取有效的Looper對象。

有參構(gòu)造

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

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

Handler類在構(gòu)造方法中,可指定Looper,Callback回調(diào)方法以及消息的處理方式(同步或異步),對于無參的Handler,默認是當前線程的Looper。

消息分發(fā)機制

Looper.loop()中,當發(fā)現(xiàn)有消息時,調(diào)用消息的目標handler,執(zhí)行dispatchMessage()方法來分發(fā)消息。

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //當Message存在回調(diào)方法,回調(diào)msg.callback.run()方法
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //當Handler存在Callback成員變量時,回調(diào)方法handleMessage()
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //Handler自身的回調(diào)方法handleMessage()
        handleMessage(msg);
    }
}

分發(fā)消息流程:

  1. Message的回調(diào)方法不為空時,則回調(diào)方法msg.callback.run,其中callback數(shù)據(jù)類型為Runnable,否則進入步驟2

  2. HandlermCallback成員變量不為空時,則回調(diào)方法mCallback.handleMessage(msg),否則進入步驟3

  3. 調(diào)用Handler自身的回調(diào)方法handleMessage(),該方法默認為空,Handler子類通過覆寫該方法來完成具體的邏輯

對于很多情況下,消息分發(fā)后的處理方式是第3種情況,即Handler.hahndleMessage(),一般往往通過覆寫改方法從而實現(xiàn)自己的業(yè)務(wù)邏輯。

消息發(fā)送

發(fā)送消息調(diào)用流程

image

其實可以從圖中看出,利用Handler發(fā)送消息,最終調(diào)用到的是MessageQueue.enqueueMessage()

sendEmptyMessage

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

sendEmptyMessageDelayed

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

sendMessageDelayed

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

sendMessageAtTime

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

sendMessageAtFrontOfQueue

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

post

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

postAtFrontOfQueue

public final boolean postAtFrontOfQueue(Runnable r) {
    return sendMessageAtFrontOfQueue(getPostMessage(r));
}

enqueueMessage

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

Handler.sendEmptyMessage()等系列方法最終調(diào)用MessageQueue.enqueueMessage(msg, uptimeMills),將消息添加到消息隊列中,其中uptimeMillis為系統(tǒng)當前的運行時間。

Handler類還有一些其他的方法

  • obtainMessage最終調(diào)用Message.obtainMessage(this),其中this為當前的Handler對象

  • removeMessage

Handler是消息機制中非常重要的輔助類,更多的是實現(xiàn)MessageQueue, Message中的方法。

MessageQueue

MessageQueue是消息機制的Java層和C++層的連接紐帶,大部分核心工作都是通過JNI中的native方法去實現(xiàn)的,涉及到下面列的方法:

private native static long nativeInit();
private native static void nativeDestroy(long ptr);
private native void nativePollOnce(long ptr, int timeoutMillis);
private native static void nativeWake(long ptr);
private native static boolean nativeIsPolling(long ptr);
private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);

創(chuàng)建MessageQueue

MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    // 調(diào)用nativeInit獲取底層的指針對象的地址mPtr,可以通過mPtr來調(diào)用底下native的接口
    mPtr = nativeInit();
}

next()

獲取下一條message

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) {     //native層的指針對象被銷毀之后就推出循環(huán)
        return null;
    }

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //調(diào)用底層阻塞函數(shù)nativePollOnce來等待消息的到來
        //等待超時時間為nextPollTimeoutMillis,等待消息來喚醒
        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);
        }

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

nativePollOnce是阻塞操作,其中nextPollTimeoutMillis代表下一個消息到來前,還需要等待的時長,當nextPollTimeoutMills=-1時,代表消息隊列中沒有消息,會無限等待下去。

當處于空閑時,會執(zhí)行IdleHandler中的方法,當nativePollOnce()返回后,next()mMessages中提取一個消息。

核心是nativePollOnce()做的事情,底下通過epoll的機制實現(xiàn)。

enqueueMessage

往消息池中添加一條消息,并且喚醒等待隊列。

boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

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

MessageQueue是按照Message觸發(fā)時間的先后順序排列的,對頭的消息是最早要觸發(fā)的。當有消息要加入消息隊列的時候,會遍歷隊列,尋找時間點插入要加入的消息,保證按照時間先后排序。

removeMessages

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        // 從頭尋找符合條件的消息移除
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        // 移除剩余符合要求的消息
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

這個一出消息的方法,采用了兩個while循環(huán),第一個循環(huán)是從隊頭開始,移除符合條件的消息,第二個循環(huán)是從頭部移除完連續(xù)的滿足條件的消息后,再從隊列后面繼續(xù)查詢會否有滿足條件的消息需要移除。

postSyncBarrier

removeSyncBarrier

前面說每一個Message必須有一個target,對于特殊的message是沒有target,即同步barrier token,這個消息的價值就是用于攔截同步消息,所以并不會喚醒Looper

Message

消息對象

每一條Message的內(nèi)容;

數(shù)據(jù)類型 成員變量 解釋
int what 消息類別
long when 消息觸發(fā)時間
int arg1 參數(shù)1
int arg2 參數(shù)2
Object obj 消息內(nèi)容
Handler target 消息響應(yīng)方
Runnable callback 回調(diào)方法

創(chuàng)建一個新消息,就是去填充這些內(nèi)容。

消息池

為了Message可以高效的重復(fù)利用,系統(tǒng)提供了消息池,當消息池不為空時,可以直接從消息池中獲取Message對象,而不是直接創(chuàng)建,提高效率。

靜態(tài)變量sPoll的數(shù)據(jù)類型為Message,通過next成員變量,維護一個消息池;靜態(tài)變量MAX_POLL_SIZE代表消息池的可用大小,消息池的默認大小為50

private static final int MAX_POOL_SIZE = 50;

消息池常用的操作方法是obtain()recycle()

obtain

從消息池中獲取消息

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next; //從sPoll中取出一個Message對象
            m.next = null;  //斷開消息鏈
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

recyle

把不用的消息放入消息池,循環(huán)利用

public void recycle() {
    if (isInUse()) {
        if (gCheckRecycle) {
            throw new IllegalStateException("This message cannot be recycled because it "
                    + "is still in use.");
        }
        return;
    }
    recycleUnchecked();
}

/**
 * Recycles a Message that may be in-use.
 * Used internally by the MessageQueue and Looper when disposing of queued Messages.
 */
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++;
        }
    }
}

recycle(),將Message加入到消息池的過程,都是把Message加到鏈表的表頭。

總結(jié)

image
  • Handler通過sendMessage()發(fā)送Message到MessageQueue隊列

  • Looper通過loop(),不斷提取出達到觸發(fā)條件的Message,并將Message交給target來處理

  • 經(jīng)過dispatchMessage()后,交回給Handler的handleMessage()進行相應(yīng)的處理

  • 將Message加入MessageQueue時,往管道寫入字符,來喚醒loop線程;如果MessageQueue中沒有Message,并處于Idle狀態(tài),則會執(zhí)行IdleHanler接口中的方法,往往用于一些清理性的工作

消息分發(fā)的優(yōu)先級

  1. Message的回調(diào)方法:message.callback.run()

  2. Handler的回調(diào)方法:Handler.mCallback.handleMessage(msg)

  3. Handler的默認方法:Handler.handleMessage(msg)

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

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

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