Android消息机制之三Handler源码分析

极客导航  2018-05-18 20:39  阅读 84 次 评论 0 条


接着《Android消息机制之一简介(1)》和《Android消息机制之二简介(2)》,我们现在来单独看看Handler源码。

设计代码的路径:

base\core\java\android\os\Handler.java

Handler的简单使用

在项目中,Handler的声明和初始化一般如下,使用默认的构造函数,当然Handler中也带参数的构造函数。

	// 使用默认构造函数
	private Handler mHandler = new Handler();

	// 使用默认构造函数,并重写handleMessage方法
	private Handler myHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

		};
	};

Handler的构造函数

下面是Handler.java所有的构造函数(好多个呢)。

Handler类在构造方法中,可指定Looper,Callback回调方法以及消息的处理方式(同步或异步),对于无参的handler,默认是当前线程的Looper。

在初始化时就会把当前线程的Looper和MessageQueue赋值到Handler中的对应变量中。然而Looper和MessageQueue的初始化是在Looper.prepare()中进行的。

同时在Handler初始化时有提示“If this thread does not have a looper, this handler won't be able to receive messages”,因此必须要有一个Looper.loop()进行循环查询消息队列。又因为loop()中是一个死循环,除非异常或者自动退出,才会执行loop后面代码,所以Handler的使用和初始化必须在Looper.loop()之前。(好像扯远了^_^)

继续看代码

    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }

    public Handler(Callback callback) {
        this(callback, false);
    }

    public Handler(Looper looper) {
        this(looper, null, false);
    }
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

    public Handler(boolean async) {
        this(null, async);
    }


    public Handler(Callback callback, boolean async) {
        //匿名类、内部类或本地类都必须申明为static,否则会警告可能出现内存泄露
        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());
            }
        }
        //获取当前线程的Looper,所以在Handler使用前Looper.prepare()
        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;
    }


    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

Handler的消息发送

直接看图,Handler可以发送的参数类型有what,Runnable,message,然后一步一步进行封装成message,最终发送的是message的

1、发送what

在项目中,发送what时是使用sendEmptyMessage、sendEmptyMessageDelayed, sendEmptyMessageAtTime的,其实这三个的作用差不多,就是延迟时间不同,其他的都是进一步把what封装

    //delayMillis延迟时间为0
    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }
     //delayMillis延迟时间,如果为0,和上面sendEmptyMessage的方法一样
     public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
    //uptimeMillis 是当前系统时间+延迟的时间(SystemClock.uptimeMillis() + delayMillis)
    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }

2、发送Message

我们会发现sendMessage()调用sendMessageDelayed()再调用sendMessageAtTime(),再调用enqueueMessage(),最终调用消息队列的enqueueMessage(),也就把message发送到MessageQueue中了。

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

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

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

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

3、发送Runnable

    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    //uptimeMillis= 是当前系统时间+延迟的时间(SystemClock.uptimeMillis() + delayMillis)
    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }
    //delayMillis 延迟
    public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

Handler.sendEmptyMessage()等一系列方法最终调用MessageQueue.enqueueMessage(msg, uptimeMillis),将消息添加到消息队列中,其中uptimeMillis为系统当前的运行时间,不包括休眠时间。

Handler的消息派发

Handler消息的分发是在Looper.loop()查询消息,然后调用msg.target.dispatchMessage(msg);进行派发,最终到了Handler中。

    /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }   

 /**
     * Subclasses must implement this to receive messages. 子类必须实现此接口
     */
    public void handleMessage(Message msg) {
    }
    
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        //如果msg中有callback,直接调用message.callback.run()
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                 //如果有mCallback,就走这里
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //这个方法要我们实现,然后处理发送来的message
            handleMessage(msg);
        }
    }

分发消息流程:

  1. 当Message的回调方法不为空时,则回调方法msg.callback.run(),其中callBack数据类型为Runnable,否则进入步骤2;
  2. 当Handler的mCallback成员变量不为空时,则回调方法mCallback.handleMessage(msg),否则进入步骤3;
  3. 调用Handler自身的回调方法handleMessage(),该方法默认为空,Handler子类通过覆写该方法来完成具体的逻辑。

其实Handler中还有很多比如移除Message,获取Message,查看是否有这条Message等等,其代码最终还是调用MessageQueue或者Message中的方法.

写了这么多,发现写得一般,算是个流水账似得.不过,自己写写总比只看不思考好多了,写的时候或许可以理理思路吧

写得不好,望见谅!

PS:本文部分内容和图片来自gityuan.com,谢谢

本文地址: https://www.125la.com/329.html
关注我们:请关注一下我们站长微信:扫描二维码125啦读书导航的微信号,微信号:yudemi(十三少)
版权声明:本文为原创或转载文章,版权归原作者所有,欢迎分享本文,转载请保留出处!
第一个读书导航

发表评论


表情