Handler 细节分析


今天总结一下这个Handler 的一些常常被问的问题,有借鉴,也有总结。如果后面还有新的问题,会添加上去。

1. Handler 机制中涉及到那些类,各自的功能是什么

主要的类就4Handler Lopper MessageQueue Message 主要是这4个

  • Handler 的作用就是将Message对象发送到MessageQueue中,同时将自己的引用赋值给Message#target
  • Looper 的作用是将Message 对象从MessageQueue中取出来,并将其交给Handler#dispatchMessage(Message) 这里需要注意的是不是调用**Handler#handleMessage(Message)**方法。
  • MessageQueue的作用就是负责插入和取出Message
  • 这里的ThreadLocal 不在此记录,因为这是JDK 中本身自带的

2. 有哪些发送消息的方法

sendMessage(Message msg)
sendMessageDelayed(Message msg,long uptimeMillis)
sendMessageAtTime(Message msg,long when)
sendEmptyMessage(int what)
sendEmptyMessageDelayed(int what,long uptimeMillis)
sendEmptyMessageAtTime(int what,long when)
Post(Runnable r)
postDelayed(Runnable r,long uptomeMillis)

方法有好多重,其实归根结底就 sendMessageAtTime(Message msg , long when) 这一个

3. MessageQueue 中的 Message 是有序的吗?排序的依据是什么

  • 是有序的。Queue都是有序的 Set 才是无序的
  • 这里的排序依据是Message#when这个字段,表示一个相对时间,改值是由 MessageQueue#enqueueMessage(Message msg , Long when) 方法设置的。
final boolean enqueueMessage(Message msg, long when) {
     // ....
        boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }

  • 当两个 Message#when 一致时插入序按先后顺序

4. Message#when 是指的是什么

Message#when 是一个时间,用于表示 Message 期望被分发的时间,该值是SystemClock#uptimeMillis()delayedMillis 之和

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

SystemClock#uptimeMillis() 是一个表示当前时间的一个相对时间,它代表的是 自系统启动开始从0开始的到调用该方法时相差的毫秒数 。

5. Message#when 为什么不用System.currentTimeMillis() 来表示

/**
     * Returns the current system time in milliseconds since January 1, 1970
     * 00:00:00 UTC. This method shouldn't be used for measuring timeouts or
     * other elapsed time measurements, as changing the system time can affect
     * the results.
     *
     * @return the local system time in milliseconds.
     */
    public static native long currentTimeMillis();

System.currentTimeMillis() 表示的是从1970-01-01 00:00:00 到当前时间的毫秒数值,我们可以通过修改系统时间达到修改改值的目的,所以改值是不可靠的值。 可能会导致 延迟消息失效
同时 Message#when 只是用 时间差 来表示先后关系,所以只需要一个相对时间就可以达到目的,它可以是从系统启动开始计时的,也可以是从APP启动开始计时的,甚至可以定期重置的,(所有消息都减去同一个值,不过这样就复杂了没有必要)。

6. 子线程中可以创建Handler 对象吗?

  • 先调用Looper.prepare() 在当前进程中初始化一个Looper
Looper.prepare();
Handler handler = new Handler();
// ....
// 这一步可别少了
Looper.loop();
  • 通过构造的形式传入一个Looper
Looper looper = .....;
Handler handler = new Handler(looper);

7. Handler 是如何与 Looper 进行关联的

  • 通过构造方法传参
  • 直接调用无参构造方法 其里面有一个自动绑定的过程 mLooper = Looper.myLooper();
   public Handler(Callback callback, boolean async) {
        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());
            }
        }

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

8. Looper 是如何与Thread 关联的

这里是通过 ThreadLocal 进行关联的,这个可以从 Looper#prepare() 方法看出来

 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
 //....
  private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

Looper 中有一个 ThreadLocal 类型的 sThreadLocal静态字段,Looper通过它的 getset 方法来赋值和取值。

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

由于 ThreadLocal是与线程绑定的,所以我们只要把 LooperThreadLocal 绑定了,那 LooperThread 也就关联上了

9. Handler 有哪些构造方法

Handler 可以传的参数仅有两种 LooperHandler#Callback
那么就可以推算出一共有多少种构造方法了 一共四种

  • 无参
  • Looper
  • Callback
  • LooperCallback
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);
}

还有一个隐藏的 boolean 的async ,不过这个不是开放的API

10. 在子线程中如何获取当前线程的 Looper

Looper.myLooper()

内部原理就是同过上面提到的 sThreadLocal#get() 来获取 Looper

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

11. 如果在任意线程获取主线程的 Looper

Looper.getMainLooper()

12.如何判断当前线程是不是主线程

  1. Looper.myLooper() == Looper.getMainLooper()
  2. Looper.getMainLooper().getThread() == Thread.currentThread()
  3. Looper.getMainLooper().isCurrentThread()

13.Looper.loop() 会退出吗?

不会自动退出,但是我们可以通过 Looper#quit() 或者 Looper#quitSafely() 让它退出。

两个方法都是调用了 MessageQueue#quit(boolean) 方法,当 MessageQueue#next() 方法发现已经调用过 MessageQueue#quit(boolean) 时会 return null 结束当前调用,否则的话即使 MessageQueue 已经是空的了也会阻塞等待。

14.MessageQueue#next 在没有消息的时候会阻塞,如何恢复?

当其他线程调用 MessageQueue#enqueueMessage 时会唤醒 MessageQueue,这个方法会被 Handler#sendMessageHandler#post 等一系列发送消息的方法调用。

boolean enqueueMessage(Message msg, long when) {
    // ...
    synchronized (this) {
        // ...
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // ...
        }
        if (needWake) {
            nativeWake(mPtr); // 唤醒
        }
    }
    return true;
}

15. Looper.loop() 方法是一个死循环为什么不会阻塞APP

因为所有让我们会觉得的卡住的都被放到了MessageQueue 里面,然后通过Looper 取出并交给 Handler 进行执行了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值