handler机制原理

时光飞逝,从事IT工作已经3年时光,以前习惯性的喜欢在CSDN上查找工作中用到的知识,CSDN真的是一个不错的学习和交流平台,都说好记星不如烂笔头,不能懒惰,以后的时光也会抽空把工作心得过来分享下,废话不多说,开始今天的知识点总结吧!


子线程mesage对象用来发送消息
Messagequeue消息队列用来存放子线程发送过来的消息mesage
looper消息循环机制用来把messagequeue的消息不断取出来并发送给handler
handler中有个handlemessage方法接收发来的消息
先看一下handle的代表性源码
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.recycle();
        }

以上代码是looper循环器的工作原理注意看这句
msg.target.dispatchMessage(msg);
我们在源码中查看target发现Handler target;代表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);
        }
    }

发现handler接收到传过来的mesage消息

以上为个人理解,如果有错误欢迎纠正

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值