Handler机制分析

背景: Handler解决线程之间发送消息

解决的问题: 

1:主线程不能执行耗时操作,ANR
2:子线程不能操作主线程的UI视图


写在前面, 首先需要明确涉及到了 4个类:

Handler的核心类:

           Message:    对发送的消息的封装
MessageQueue:    消息队列,存放所有的消息
              Looper:  可以循环读取消息(从MessageQueue中读取)
             Handler:    处理消息,同时也是发送消息的


1. Message: 消息包装类, 并且包含一个target属性成员(Handler在发送它时Handler自己就被赋值:                    msg.target=handler)


Message msg = Message.obtain();
msg.obj ="hello,你好!";
handler.sendMessage(msg);

2. MessageQueue: 是由Looper创建, 它主要存放Message


3. Looper: 在本线程中保存Looper实例和MessageQueue实例, 它的loop方法在MessageQueue当中取Message


Looper类:


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


public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(true));
}


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

Looper主要作用:
1. 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
2.  loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。

     还记得上面说的Message的target属性吧, 没错就是Handler调用了dispatchMessage, dispatchMessage是个什么鬼?下面看源码:

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

 handleMessage(msg);这句就是关键所在, 对这个是要我们接收方重写的, 也就是处理消息


最后注意:


1 主线程必须要有 handler的引用(线程之间使用同一个handler)

2 主线程一启动就会创建主线程的looper:  调用Looper.prepare()和Looper.loop()方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值