Android開發藝術探索 - 第10章 Android的消息機制

1.概述

Handler的作用是將一個任務切換到指定的線程去執行。
UI操作只能在主線程進行,這個限制是在ViewRootImpl#checkThread中實現的:

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}

Handler工作原理:

  • Handler創建時,會採用當前線程的Looper來構建內部的消息循環,如果當前線程沒有Looper,會拋出異常。
  • 通過Handler的send發送一個msg,或者直接post一個Runnable,最終都會由Looper去執行handleMessage或Runnable,而Looper是在創建Handler所在的線程中運行的,所以實現了線程切換。

2.消息機制分析

  1. ThreadLocal的工作原理
    ThreadLocal是一個線程內部的存儲類,可以在指定的線程中存儲數據,且這份數據僅供這個線程獲取。其應用場景是,當某些數據是以線程爲作用域並且不同線程具有不得數據副本。如Handler中的Looper,每個線程都有自己的Looper且互不相同。
    另外一個使用場景,是在複雜邏輯下的對象傳遞,使該對象作爲線程內的全局對象存在,在線程內部通過get方法就可以獲得該對象。
    ThreadLocal是個泛型類,創建一個ThreadLocal實例:
    private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal();
    

當分別從主線程,子線程去獲取該ThreadLocal的值時,他們分別會得到自己的線程中對應的ThreaLocal的值:

mBooleanThreadLocal.set(true);
Boolean value = mBooleanThreadLocal.get();      // true

new Thread(new Runnable() {
    @Override
    public void run() {
        Boolean value = mBooleanThreadLocal.get();      // null

        mBooleanThreadLocal.set(false);
        value = mBooleanThreadLocal.get();      // false
    }
}).start();

ThreadLocal#set,每個線程中都有一個ThreadLocalMap,用於存儲<ThreadLocal<T>, T>,每在一個線程中調用ThreadLocal#set,就會將這個類型的ThreadLocal以及其泛型的值存儲進map:

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

ThreadLocal#get,首先會嘗試從ThreadLocalMap取與該ThreadLocal類型對應的其泛型的值,如果找不到,調用setInitialValue方法,通過initialValue方法得到初始值,然後如果ThreadLocalMap也不存在,則同時創建ThreadLocalMap,最後添加進map中:

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}
private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

initialValue方法的默認實現返回了null,可以依據具體ThreadLocal的泛型類型,重寫該方法。
2. MessageQueue工作原理
enqueueMessage方法,MessageQueue內部通過單鏈表維護msg隊列,入隊的過程與隊列類似,只是其中會根據msg的when字段,判斷合適的入隊位置,並不一定是隊尾:

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

next方法,會嘗試獲取下一個msg,如果獲取到則從隊列中刪除並返回這個msg;如果沒有msg則阻塞。新msg的到來nativePollOnce就會返回:

    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;
                }
            ...
        }
    }
  1. Looper工作原理
    Looper的構造方法,創建了MessageQueue,同時將當前的線程對象保存起來:
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

啓動Looper的例子:

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

在prepare方法中,創建了Looper對象,同時使用ThreadLocal存儲了該Looper:

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

除了prepare方法,Looper提供了prepareMainLooper方法,用於ActivityThread創建主線程Looper使用,其本質也是通過prepare來實現的。同時提供了getMainLooper方法,在其他線程中獲取主線程的Looper。
Looper完成操作之後,需要調用quit或quitSafely退出,前者會直接退出,後者設置了一個標記,待所有的msg處理完畢再退出。如果子線程不調用quit,該線程會一直阻塞,直到調用quit時直接退出。Looper調用了quit之後,Handler發出的msg將失敗,send方法會返回false。

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

loop方法,在該方法中真正處理了MessageQueue中的msg。首先通過ThreadLocal獲得當前線程的Looper實例,然後開始取其MessageQueue中的msg,如果Looper調用了quit方法,這裏取得的msg就是null,對應的Looper就會退出loop;如果取到了msg,就會調用msg.target.dispatchMessage(msg)執行Handler的dispatchMessage方法。MessageQueue中沒有msg時,則阻塞:

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;

    ...

    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...
        try {
            msg.target.dispatchMessage(msg);
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        ...
}
  1. Handler的工作原理
    Handler主要負責msg的發送和接收。post方法會將Runnable封裝成msg,然後調用send發出msg:
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;
}

send的一系列方法,最終會將msg添加到MessageQueue中:

public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
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);
}

MessageQueue#enqueueMessage方法在msg添加之後,會執行nativeWake方法,如果之前MessageQueue因爲是空的而阻塞在next方法中,這時阻塞解除,開始獲取msg。Looper得到MessageQueue的msg,調用Handler的dispatchMessage方法。
這裏分幾種情況:對於通過post方法傳入的Runnable,則直接通過handleCallback方法去執行他;對於send方法傳入的msg,首先會交由其mCallback的handleMessage方法去處理,該回調可以在創建Handler時指定,就不必重寫Handler的handleMessage方法;如果該回調沒有處理,即返回了false,則交由Handler自己的handleMessage處理:

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

Handler的構造方法中,會判斷當前線程的Looper是否存在,不存在則拋出異常。同時會獲取Looper的MessageQueue以便後續添加msg:

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;

3.主線程消息循環

Android的主線程就是ActivityThread,其main方法中,創建了主線程Looper,並啓動了消息循環:

    public static void main(String[] args) {
        ...

        Looper.prepareMainLooper();
        ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

負責處理消息的Handler即ActivityThread.H,其中就包括了四大組件的啓動和停止過程:

class H extends Handler {
    public static final int BIND_APPLICATION        = 110;
    public static final int EXIT_APPLICATION        = 111;
    public static final int RECEIVER                = 113;
    public static final int CREATE_SERVICE          = 114;
    public static final int SERVICE_ARGS            = 115;
    public static final int STOP_SERVICE            = 116;

主線程消息循環模型:

  • ActivityThread提供ApplicationThread與AMS進行IPC
  • AMS完成了ActivityThread的RPC之後,回調ApplicationThread中的遠程方法
  • ApplicationThread爲Binder對象,其方法運行在Binder線程池中
  • ApplicationThread通過H發送msg給ActivityThread的MessageQueue,Looper取出msg,在主線程中處理相應的msg
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章