3.1 Handler是如何关联消息队列和线程的?
我们首先看Handler默认的构造函数:
public Handler(Callback callback, boolean async) {
//代码省略
mLooper = Looper.myLooper();//获取Looper
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//通过Looper对象获取消息队列
mCallback = callback;
mAsynchronous = async;
}
//获取Looper对象
public final Looper getLooper() {
return mLooper;
}
从Handler的构造函数中我们可以发现,Handler在初始化的同时会通过Looper.getLooper()获取一个Looper对象,并与Looper进行关联,然后通过Looper对象获取消息队列。那我们继续深入到Looper源码中去看Looper.getLooper()是如何实现的。
//初始化当前线程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();
}
}
//为当前线程设置一个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));
}
从上面的程序可以看出通过prepareMainLooper(),然后调用 prepare(boolean quitAllowed)方法创建了一个Looper对象,并通过sThreadLocal.set(new Looper(quitAllowed))方法将该对象设置给了sThreadLocal。
//通过ThreadLocal获取Looper
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
通过Looper中的预备工作,sThreadLocal中已经存储了一个Looper对象,然后myLoop