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 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,用于存储, 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

你可能感兴趣的:(编程,Android,Java)