深入理解Looper,MessageQueue和Handler

这几乎是每次面试必问的问题了吧,然而并没有什么高深,之所以每次面试问,是由于Handler在平时工作中用的比较多,记得当年去vivo面试,问了两个技术点,这是其中一个,先从整体说一下,每个线程只能有一个Looper,Looper里面会创建一个消息队列MessageQueue,Handler在发消息的时候找到当前Looper的MessageQueue,然后把消息传进去,Looper里面有个无限循环,不断从MessageQueue里读消息,并交还给发消息的Handler进行处理。。。有点绕?看源码,我们一句一句来解释

一 每个线程只能有一个Looper,Looper里面会创建一个消息队列MessageQueue

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

构造函数创建了一个MessageQueue,没什么好说的,接下来是大家平时用的最多的prepare

public static void prepare() {
        prepare(true);
    }

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

看到这里,quitAllowed是什么呢,找到MessageQueue的构造函数

MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }
void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

看到这里明白了,主线程的消息队列是不允许退出,由于主线程的Looper创建不需要我们管,我们一般创建的Looper默认这个值就是true,回过头来看prepare,里面new了一个Looper存到sThreadLocal中,并且第二次进入,sThreadLocal.get()不为空就会报异常,每个线程只能创建一个Looper对象,这里应该清晰了吧,接下来看Handler:
二 Handler在发消息的时候找到当前Looper的MessageQueue,然后把消息传进去

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

Handler通过Looper.myLooper()获得当前线程的Looper对象

public static Looper myLooper() {
        return sThreadLocal.get();
    }

然后再通过mLooper.mQueue获取到Looper里创建的MessageQueue,好,接下来看我们常用的sendMessage方法:

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

里面其实是调用了sendMessageDelayed方法

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

再往里调用了sendMessageAtTime方法:

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

最终调用enqueueMessage把消息放到消息队列中

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

注意msg.target = this;这句话,把当前handler对象赋给msg.target,这个待会会用到
三 Looper里面有个无限循环,不断从MessageQueue里读消息,并交还给发消息的Handler进行处理。。。
看Looper里的loop方法:

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;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

final Looper me = myLooper(); 获取当前Looper,final MessageQueue queue = me.mQueue;获取到当前MessageQueue,接下来就是个无限循环for (;;) {Message msg = queue.next();不断的从消息队列中取出消息,然后调用msg.target.dispatchMessage(msg);处理,前面说了msg.target里存的就是发消息的Handler,这样的话直接调用了Handler的dispatchMessage方法:

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

最终就会回调到我们重写的handlerMessage处理消息了。
总结一下,还是那三句话
1 每个线程只能有一个Looper,Looper里面会创建一个消息队列MessageQueue
2 Handler在发消息的时候找到当前Looper的MessageQueue,然后把消息传进去
3 Looper里面有个无限循环,不断从MessageQueue里读消息,并交还给发消息的Handler进行处理。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值