Android消息循环机制

2017-06-08  本文已影响0人  stefanJi

在非UI线程使用Handler进行线程通信时,一般都需要进行3个步骤:

loop-prepare

通过这3步,基本就建立好了Android的多线程消息通信机制:

这几者可谓是你中有我,我中有你的存在......

但是,能够实现这样的机制是因为有一个重要的东西存在:ThreadLocal.彻底理解ThreadLocal

Looper中存在一个静态的常量sThreadLocal就是供各个线程独享的。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

Looper.prepar()

在这里面主要执行了2步:

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

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}

创建Handler

创建Handler时主要进行了将Handler与Looper绑定的操作:

mLooper = Looper.myLooper();
if (mLooper == null) {
       throw new RuntimeException(
          "Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;

Looper.loop()

如有问题,欢迎指出_

上一篇 下一篇

猜你喜欢

热点阅读