你真的懂Android Handler吗?(一)

你真的懂Android的Handler机制吗?在回答这个问题之前先问自己几个问题:

1、Handler是如何跟线程绑定的?

2、Handler中的消息是怎么传递的?是通过回调还是通过循环?

3、如果是通过循环传递的,那么为什么消息队列为空时没有引起ANR?是不是在非UI线程中进行的无限循环?

4、如果是在非UI线程中进行的无限循环,那么在UI线程发送消息并且在UI线程中处理消息时是否进行了线程切换?这样做是否浪费了资源?有没有更好的解决方案?

5、Handler是如何进行线程切换的?

我们从Handler对象的创建入手,深挖一下Handler消息机制。

 

模块一:Hander是如何跟线程绑定的?

首先看Handler的无参构造函数:

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

猜你喜欢

转载自blog.csdn.net/kanglupeng/article/details/105365329