Handler中几个类型关系图以及使用Handler常用问题

从上面的文章中我们已经知道了Handler,MessageQuene,Message的源码,Looper也看了loop方法,但是我们还漏调了Looper.prepare()方法,好那我们就来看这个源码:



构造方法是私有的所以我们不能直接new,那我们怎么创建一个Looper对象呢?

/**
 * Return the Looper object associated with the current thread.  Returns
 * null if the calling thread is not associated with a Looper.
 */
public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

从threadLocal中获取looper,并且有可能返回空,返回空的情况一般为在异步线程中没有调用Looper.prepare()。ThreadLocal到底是个神马东西,大概意思是这样子的:
ThreadLocal的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。以后章节会详细介绍。在这里只需要记住用这个来保证一个线程只有一个Looper继而保证只有一个消息队列。
接下来我们再来看另外一个prepare()方法:

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

可以看出如果当前获取的Looper为空会报错。这样也保证一个线程只有一个Looper继而保证只有一个MessageQuene。好了源码就讲到这儿,我们最后通过一个完整的图来整理源码中的知识点


image.png
image.png

你可能感兴趣的:(Handler中几个类型关系图以及使用Handler常用问题)