Handler机制原理

2019-07-12  本文已影响0人  玖玖君

handler机制用来实现线程之间的通信;

1、 概述

Handler 、 Looper 、Message 、MessageQueue都与Android异步消息处理线程相关的概念.

那么和Handler 、 Looper 、Message、MessageQueue有啥关系?其实Looper负责的就是创建一个MessageQueue,然后进入一个无限循环体不断从该MessageQueue中读取消息,而消息的创建者就是一个或多个Handler 。

2、 图解

image

3、 源码分析

1.new Handler()
        --->this(null, false); 
        --->Looper mLooper = Looper.myLooper();
        --->MessageQueue mQueue =  mLooper.mQueue

2.handler.sendMessage(message);
        --->sendMessageAtTime()
        --->enqueueMessage(queue, msg, uptimeMillis)
        --->msg.target = this;  ---  Handler对象
        --->queue.enqueueMessage(msg, uptimeMillis)

3.Looper
    prepare():
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));

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

        注意:一个线程中只能有一个Looper对象,只能有一个消息队列MessageQueue

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

            。。。。

            msg.target.dispatchMessage(msg);  ---  handler

        }

4.handler.dispatchMessage():
        if (msg.callback != null) {
            handleCallback(msg); --- >回调自身Runnable中run方法
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg); --- >子类必须重写
        }

        回到最后处理的方法:
            private static void handleCallback(Message message) {
                message.callback.run();
            }

            /**
             * Subclasses must implement this to receive messages.
             */
            public void handleMessage(Message msg) {
            }

4、 总结

  1. Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。

  2. Handler的sendMessage方法,会给msg的target赋值为handler自身,然后将Message加入MessageQueue中。

  3. Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。

  4. Looper.loop()会让当前线程进入一个无限循环,从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。

  5. handler.dispatchMessage(msg)分发消息,如果是sendMessage(),会回调重写的handleMessage方法;如果是post(),会最后会回调 message.callback.run(),当前的run()方法。

  6. 在Activity中,我们并没有显示的调用Looper.prepare()和Looper.loop()方法,为啥Handler可以成功创建呢,这是因为在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。

上一篇下一篇

猜你喜欢

热点阅读