Handler机制源码分析

1.构造函数

Handler的构造函数有四个,在构造函数中获取了Looper对象和MessageQueue消息队列

每个Handler对应一个Looper对象和MessageQueue对象

让Handler处理消息有两种方法:

  • 向Handler构造方法中传入Handler.Callback对象,并实现Handler.Callback的handleMessage方法
  • 无需向Hanlder的构造函数传入Handler.Callback对象,但是需要重写Handler本身的handleMessage方法

2.Handler发送消息

//发送消息
    public final boolean sendMessage(Message msg)
    {   
        //调用延时发送
        return sendMessageDelayed(msg, 0);
    }
    //延时发送
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        //调用sendMessageAtTime
        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;
        }
        //调用enqueueMessage
        return enqueueMessage(queue, msg, uptimeMillis);
    }
    //enqueueMessage
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        //设置设置msg.target为当前handler对象
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //将消息添加的消息队列中
        return queue.enqueueMessage(msg, uptimeMillis);
    }

通过上述代码可以看出Handler发送消息有多种方式,但是最后都会调用sendMessageAtTime()方法,sendMessageAtTime()最后会调用enqueueMessage()方法,该方法会设置msg.target为当前的handler对象,并将消息添加到队列中。

所以创建Handler对象时只是得到了当前线程的Looper对象和MessageQueue队列,在handler对象发送消息的时候才会将设置target并且将消息添加到消息队列中。

3.Looper原理分析

Android在启动运行主线程main()方法的时候调用了Looper中的prepare()和looper()方法,为主线程事先创建了Looper对象并启动了消息循环。

prepare()方法流程

public static void prepare() {
         prepare(true);
     }
     private static void prepare(boolean quitAllowed) {
        //证了一个线程中只有一个Looper实例
        if (sThreadLocal.get() != null) {
         throw new RuntimeException("Only one Looper may be created per thread");
        }
        //通过ThreadLocal实现Looper实例和线程的绑定
        sThreadLocal.set(new Looper(quitAllowed));
    }
    //构造方法实例化当前的MessageQueue和当前线程
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    } 

    public static MessageQueue myQueue() {
        return myLooper().mQueue;
    }

looper()方法流程

public static void loop() {
        final Looper me = myLooper();
        //获取looper并且不能为空
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
        //for循环通过MessageQueue中的next()方法获取消息队列中的消息
        Message msg = queue.next(); // might block
        if (msg == null) {
            return;
        }

        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
            msg.callback + ": " + msg.what);
        }
        //调用绑定的target也就是消息的handler对象执行对消息的处理
        msg.target.dispatchMessage(msg);

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

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

Handler中的dispatchMessage()方法如下

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

在上述代码中可以看到消息最终被handler对象的handleMessage()方法处理了。

4.在子线程中使用Handler

因为子线程使我们手动创建的,并没有Looper和MessageQueue,所以需要我们自己创建。
在子线程中使用Handler需要三步

  • 1.调用Looper的prepare()方法,为当前线程创建looper对象,然后将looper对象与当前线程绑定。在创建looper对象的时候会同时创建MessageQueue消息队列对象,这样Looper对象有了,MessageQueue对象也有了。
  • 然后重写handler对象的handleMessage()方法或者传入Handler.Callback对象重写其中的handleMessage()方法。
  • 调用Looper的looper()方法让循环启动起来通过队列中的next()方法获取消息然后调用handleMessage()处理消息。

5.总结

  • Handler:将消息发送给Looper管理的MessageQueue,处理Looper分发的消息
  • Looper:每个线程只有一个Looper,负责管理对应的MessageQueue,并不断的从MessageQueue中取出消息交给handler处理。Android中主线程已经为我们创建好了Looper对象,所以可以直接使用handler发送和处理消息。应用自己创建的子线程需要调用Looper的prepare()方法来创建Looper对象和MessageQueue对象并将线程与Looper对象绑定,然后调用Looper的looper()循环从消息队列中取出消息分发给handler处理
  • Message:消息对象
  • MessageQueue:消息队列,它由Looper管理,通过先进先出的原则管理Message。Handler的构造方法会获取当前线程对应的Looper对象,并通过Looper对象获取MessageQueue对象。当Handler对象调用发送消息的时候会将自身赋给msg.target,并将消息加入的MessageQueue中。

QQ交流群

微信公众号:Android在路上,欢迎关注

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值