[关闭]
@TryLoveCatch 2022-05-06T02:28:50.000000Z 字数 53360 阅读 1039

Android知识体系之Handler

Android知识体系


总览

Handler 在整个 Android 开发体系中占据着很重要的地位,对开发者来说起到的作用很明确,就是为了实现线程切换或者是执行延时任务,稍微更高级一点的用法可能是为了保证多个任务在执行时的有序性。由于 Android 系统中的主线程有特殊地位,所以像 EventBus 和 Retrofit 这类并非 Android 独有的三方库,都是通过 Handler 来实现对 Android 系统的特殊平台支持。大部分开发者都已经对如何使用 Handler 很熟悉了,这里就再来了解下其内部具体是如何实现的

本文基于 Android API 30(即 Android 11)的系统源码进行讲解

一、动手实现 Handler

本文不会一上来就直接介绍源码,而是会先根据我们想要实现的效果来反推源码,一步步来自己动手实现一个简单的 Handler

1、Message

首先,我们需要有个载体来表示要执行的任务,就叫它 Message 吧,Message 应该有什么参数呢?

所以,Message 类就应该至少包含以下几个字段:

  1. /**
  2. * @Author: leavesC
  3. * @Date: 2020/12/1 13:31
  4. * @Desc:
  5. * GitHub:https://github.com/leavesC
  6. */
  7. public final class Message {
  8. //唯一标识
  9. public int what;
  10. //数据
  11. public Object obj;
  12. //时间戳
  13. public long when;
  14. }

2、MessageQueue

因为 Message 并不是发送了就能够马上被消费掉,所以就肯定要有个可以用来存放的地方,就叫它 MessageQueue 吧,即消息队列。Message 可能需要延迟处理,那么 MessageQueue 在保存 Message 的时候就应该按照时间戳的大小来顺序存放,时间戳小的 Message 放在队列的头部,在消费 Message 的时候就直接从队列头取值即可

那么用什么数据结构来存放 Message 比较好呢?

好了,既然决定用链表结构,那么 Message 就需要增加一个字段用于指向下一条消息才行

  1. /**
  2. * @Author: leavesC
  3. * @Date: 2020/12/1 13:31
  4. * @Desc:
  5. * GitHub:https://github.com/leavesC
  6. */
  7. public final class Message {
  8. //唯一标识
  9. public int what;
  10. //数据
  11. public Object obj;
  12. //时间戳
  13. public long when;
  14. //下一个节点
  15. public Message next;
  16. }

MessageQueue 需要提供一个 enqueueMessage方法用来向链表插入 Message,由于存在多个线程同时向队列发送消息的可能,所以方法内部还需要做下线程同步才行

  1. /**
  2. * @Author: leavesC
  3. * @Date: 2020/12/1 13:31
  4. * @Desc:
  5. * GitHub:https://github.com/leavesC
  6. */
  7. public class MessageQueue {
  8. //链表中的第一条消息
  9. private Message mMessages;
  10. void enqueueMessage(Message msg, long when) {
  11. synchronized (this) {
  12. Message p = mMessages;
  13. //如果链表是空的,或者处于队头的消息的时间戳比 msg 要大,则将 msg 作为链表头部
  14. if (p == null || when == 0 || when < p.when) {
  15. msg.next = p;
  16. mMessages = msg;
  17. } else {
  18. Message prev;
  19. //从链表头向链表尾遍历,寻找链表中第一条时间戳比 msg 大的消息,将 msg 插到该消息的前面
  20. for (; ; ) {
  21. prev = p;
  22. p = p.next;
  23. if (p == null || when < p.when) {
  24. break;
  25. }
  26. }
  27. msg.next = p;
  28. prev.next = msg;
  29. }
  30. }
  31. }
  32. }

此外,MessageQueue 要有一个可以获取队头消息的方法才行,就叫做next()吧。外部有可能会随时向 MessageQueue 发送 Message,next()方法内部就直接来开启一个无限循环来反复取值吧。如果当前队头的消息可以直接处理的话(即消息的时间戳小于或等于当前时间),那么就直接返回队头消息。而如果队头消息的时间戳比当前时间还要大(即队头消息是一个延时消息),那么就计算当前时间和队头消息的时间戳的差值,计算 next() 方法需要阻塞等待的时间,调用 nativePollOnce()方法来等待一段时间后再继续循环遍历

  1. //用来标记 next() 方法是否正处于阻塞等待的状态
  2. private boolean mBlocked = false;
  3. Message next() {
  4. int nextPollTimeoutMillis = 0;
  5. for (; ; ) {
  6. nativePollOnce(nextPollTimeoutMillis);
  7. synchronized (this) {
  8. //当前时间
  9. final long now = SystemClock.uptimeMillis();
  10. Message msg = mMessages;
  11. if (msg != null) {
  12. if (now < msg.when) {
  13. //如果当前时间还未到达消息的的处理时间,那么就计算还需要等待的时间
  14. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
  15. } else {
  16. //可以处理队头的消息了,第二条消息成为队头
  17. mMessages = msg.next;
  18. msg.next = null;
  19. mBlocked = false;
  20. return msg;
  21. }
  22. } else {
  23. // No more messages.
  24. nextPollTimeoutMillis = -1;
  25. }
  26. mBlocked = true;
  27. }
  28. }
  29. }
  30. //将 next 方法的调用线程休眠指定时间
  31. private void nativePollOnce(long nextPollTimeoutMillis) {
  32. }

此时就需要考虑到一种情形:next()还处于阻塞状态的时候,外部向消息队列插入了一个可以立即处理或者是阻塞等待时间比较短的 Message。此时就需要唤醒休眠的线程,因此 enqueueMessage还需要再改动下,增加判断是否需要唤醒next()方法的逻辑

  1. void enqueueMessage(Message msg, long when) {
  2. synchronized (this) {
  3. //用于标记是否需要唤醒 next 方法
  4. boolean needWake = false;
  5. Message p = mMessages;
  6. //如果链表是空的,或者处于队头的消息的时间戳比 msg 要大,则将 msg 作为链表头部
  7. if (p == null || when == 0 || when < p.when) {
  8. msg.next = p;
  9. mMessages = msg;
  10. //需要唤醒
  11. needWake = mBlocked;
  12. } else {
  13. Message prev;
  14. //从链表头向链表尾遍历,寻找链表中第一条时间戳比 msg 大的消息,将 msg 插到该消息的前面
  15. for (; ; ) {
  16. prev = p;
  17. p = p.next;
  18. if (p == null || when < p.when) {
  19. break;
  20. }
  21. }
  22. msg.next = p;
  23. prev.next = msg;
  24. }
  25. if (needWake) {
  26. //唤醒 next() 方法
  27. nativeWake();
  28. }
  29. }
  30. }
  31. //唤醒 next() 方法
  32. private void nativeWake() {
  33. }

3、Handler

既然存放消息的地方已经确定就是 MessageQueue 了,那么自然就还需要有一个类可以用来向 MessageQueue 发送消息了,就叫它 Handler 吧。Handler 可以实现哪些功能呢?

所以说,Message 的定义和发送是由 Handler 来完成的,但 Message 的分发则可以交由其他线程来完成

根据以上需求:Runnable 要能够包装为 Message 类型,Message 的处理逻辑要交由 Handler 来定义,所以 Message 就还需要增加两个字段才行

  1. /**
  2. * @Author: leavesC
  3. * @Date: 2020/12/1 13:31
  4. * @Desc:
  5. * GitHub:https://github.com/leavesC
  6. */
  7. public final class Message {
  8. //唯一标识
  9. public int what;
  10. //数据
  11. public Object obj;
  12. //时间戳
  13. public long when;
  14. //下一个节点
  15. public Message next;
  16. //用于将 Runnable 包装为 Message
  17. public Runnable callback;
  18. //指向 Message 的发送者,同时也是 Message 的最终处理者
  19. public Handler target;
  20. }

Handler 至少需要包含几个方法:用于发送 Message 和 Runnable 的方法、用来处理消息的 handleMessage 方法、用于分发消息的 dispatchMessage方法

  1. /**
  2. * @Author: leavesC
  3. * @Date: 2020/12/1 13:31
  4. * @Desc:
  5. * GitHub:https://github.com/leavesC
  6. */
  7. public class Handler {
  8. private MessageQueue mQueue;
  9. public Handler(MessageQueue mQueue) {
  10. this.mQueue = mQueue;
  11. }
  12. public final void post(Runnable r) {
  13. sendMessageDelayed(getPostMessage(r), 0);
  14. }
  15. public final void postDelayed(Runnable r, long delayMillis) {
  16. sendMessageDelayed(getPostMessage(r), delayMillis);
  17. }
  18. public final void sendMessage(Message r) {
  19. sendMessageDelayed(r, 0);
  20. }
  21. public final void sendMessageDelayed(Message msg, long delayMillis) {
  22. if (delayMillis < 0) {
  23. delayMillis = 0;
  24. }
  25. sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
  26. }
  27. public void sendMessageAtTime(Message msg, long uptimeMillis) {
  28. msg.target = this;
  29. mQueue.enqueueMessage(msg, uptimeMillis);
  30. }
  31. private static Message getPostMessage(Runnable r) {
  32. Message m = new Message();
  33. m.callback = r;
  34. return m;
  35. }
  36. //由外部来重写该方法,以此来消费 Message
  37. public void handleMessage(Message msg) {
  38. }
  39. //用于分发消息
  40. public void dispatchMessage(Message msg) {
  41. if (msg.callback != null) {
  42. msg.callback.run();
  43. } else {
  44. handleMessage(msg);
  45. }
  46. }
  47. }

之后,子线程就可以像这样来使用 Handler 了:将子线程持有的 Handler 对象和主线程关联的 mainMessageQueue 绑定在一起,主线程负责循环从 mainMessageQueue 取出 Message 后再来调用 Handler 的 dispatchMessage 方法,以此实现线程切换的目的

  1. Handler handler = new Handler(mainThreadMessageQueue) {
  2. @Override
  3. public void handleMessage(Message msg) {
  4. switch (msg.what) {
  5. case 1: {
  6. String ob = (String) msg.obj;
  7. break;
  8. }
  9. case 2: {
  10. List<String> ob = (List<String>) msg.obj;
  11. break;
  12. }
  13. }
  14. }
  15. };
  16. Message messageA = new Message();
  17. messageA.what = 1;
  18. messageA.obj = "https://github.com/leavesC";
  19. Message messageB = new Message();
  20. messageB.what = 2;
  21. messageB.obj = new ArrayList<String>();
  22. handler.sendMessage(messageA);
  23. handler.sendMessage(messageB);

4、Looper

现在就再来想想怎么让 Handler 拿到和主线程关联的 MessageQueue,以及主线程怎么从 MessageQueue 获取 Message 并回调 Handler。这之间就一定需要一个中转器,就叫它 Looper 吧。Looper 具体需要实现什么功能呢?

这样,Looper 的大体框架就出来了。通过 ThreadLocal 来为不同的线程单独维护一个 Looper 实例,每个线程通过 prepare()方法来初始化本线程独有的 Looper 实例 ,再通过 myLooper()方法来获取和当前线程关联的 Looper 对象,和主线程关联的 sMainLooper 作为静态变量存在,方便子线程获取

  1. /**
  2. * @Author: leavesC
  3. * @Date: 2020/12/1 13:31
  4. * @Desc:
  5. * GitHub:https://github.com/leavesC
  6. */
  7. final class Looper {
  8. final MessageQueue mQueue;
  9. final Thread mThread;
  10. private static Looper sMainLooper;
  11. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  12. private Looper() {
  13. mQueue = new MessageQueue();
  14. mThread = Thread.currentThread();
  15. }
  16. public static void prepare() {
  17. if (sThreadLocal.get() != null) {
  18. throw new RuntimeException("Only one Looper may be created per thread");
  19. }
  20. sThreadLocal.set(new Looper());
  21. }
  22. public static void prepareMainLooper() {
  23. prepare();
  24. synchronized (Looper.class) {
  25. if (sMainLooper != null) {
  26. throw new IllegalStateException("The main Looper has already been prepared.");
  27. }
  28. sMainLooper = myLooper();
  29. }
  30. }
  31. public static Looper getMainLooper() {
  32. synchronized (Looper.class) {
  33. return sMainLooper;
  34. }
  35. }
  36. public static Looper myLooper() {
  37. return sThreadLocal.get();
  38. }
  39. }

Looper 还需要有一个用于循环从 MessageQueue 获取消息并处理的方法,就叫它loop()吧。其作用也能简单,就是循环从 MessageQueue 中取出 Message,然后将 Message 再反过来分发给 Handler 即可

  1. public static void loop() {
  2. final Looper me = myLooper();
  3. if (me == null) {
  4. throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
  5. }
  6. final MessageQueue queue = me.mQueue;
  7. for (; ; ) {
  8. Message msg = queue.next();//可能会阻塞
  9. msg.target.dispatchMessage(msg);
  10. }
  11. }

这样,主线程就先通过调用prepareMainLooper()来完成 sMainLooper 的初始化,然后调用loop()开始向 mainMessageQueue 循环取值并进行处理,没有消息的话主线程就暂时休眠着。子线程拿到 sMainLooper 后就以此来初始化 Handler,这样子线程向 Handler 发送的消息就都会被存到 mainMessageQueue 中,最终在主线程被消费掉

5、做一个总结

这样一步步走下来后,读者对于 Message、MessageQueue、Handler、Looper 这四个类的定位就应该都很清晰了吧?不同线程之间就可以依靠拿到对方的 Looper 来实现消息的跨线程处理了

例如,对于以下代码,即使 Handler 是在 otherThread 中进行初始化,但 handleMessage 方法最终是会在 mainThread 被调用执行的,

  1. Thread mainThread = new Thread() {
  2. @Override
  3. public void run() {
  4. //初始化 mainLooper
  5. Looper.prepareMainLooper();
  6. //开启循环
  7. Looper.loop();
  8. }
  9. };
  10. Thread otherThread = new Thread() {
  11. @Override
  12. public void run() {
  13. Looper mainLooper = Looper.getMainLooper();
  14. Handler handler = new Handler(mainLooper.mQueue) {
  15. @Override
  16. public void handleMessage(Message msg) {
  17. switch (msg.what) {
  18. case 1: {
  19. String ob = (String) msg.obj;
  20. break;
  21. }
  22. case 2: {
  23. List<String> ob = (List<String>) msg.obj;
  24. break;
  25. }
  26. }
  27. }
  28. };
  29. Message messageA = new Message();
  30. messageA.what = 1;
  31. messageA.obj = "https://github.com/leavesC";
  32. Message messageB = new Message();
  33. messageB.what = 2;
  34. messageB.obj = new ArrayList<String>();
  35. handler.sendMessage(messageA);
  36. handler.sendMessage(messageB);
  37. }
  38. };

再来做个简单的总结:

有了以上的认知基础后,下面就来看看实际的源码实现 ~ ~

二、Handler 源码

1、Handler 如何初始化

Handler 的构造函数一共有七个,除去两个已经废弃的和三个隐藏的,实际上开发者可以使用的只有两个。而不管是使用哪个构造函数,最终的目的都是为了完成 mLooper、mQueue、mCallback、mAsynchronous 这四个常量的初始化,同时也可以看出来 MessageQueue 是由 Looper 来完成初始化的,而且 Handler 对于 Looper 和 MessageQueue 都是一对一的关系,一旦初始化后就不可改变

大部分开发者使用的应该都是 Handler 的无参构造函数,而在 Android 11 中 Handler 的无参构造函数已经被标记为废弃的了。Google 官方更推荐的做法是通过显式传入 Looper 对象来完成初始化,而非隐式使用当前线程关联的 Looper

Handler 对于 Looper 和 MessageQueue 都是一对一的关系,但是 Looper 和 MessageQueue 对于 Handler 可以是一对多的关系,这个后面会讲到

  1. @UnsupportedAppUsage
  2. final Looper mLooper;
  3. final MessageQueue mQueue;
  4. @UnsupportedAppUsage
  5. final Callback mCallback;
  6. final boolean mAsynchronous;
  7. //省略其它构造函数
  8. /**
  9. * @hide
  10. */
  11. public Handler(@Nullable Callback callback, boolean async) {
  12. if (FIND_POTENTIAL_LEAKS) {
  13. final Class<? extends Handler> klass = getClass();
  14. if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
  15. (klass.getModifiers() & Modifier.STATIC) == 0) {
  16. Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
  17. klass.getCanonicalName());
  18. }
  19. }
  20. mLooper = Looper.myLooper();
  21. if (mLooper == null) {
  22. throw new RuntimeException(
  23. "Can't create handler inside thread " + Thread.currentThread()
  24. + " that has not called Looper.prepare()");
  25. }
  26. mQueue = mLooper.mQueue;
  27. mCallback = callback;
  28. mAsynchronous = async;
  29. }

2、Looper 如何初始化

在初始化 Handler 时,如果外部调用的构造函数没有传入 Looper,那就会调用Looper.myLooper()来获取和当前线程关联的 Looper 对象,再从 Looper 中取 MessageQueue。如果获取到的 Looper 对象为 null 就会抛出异常。根据异常信息 Can't create handler inside thread that has not called Looper.prepare() 可以看出来,在初始化 Handler 之前需要先调用 Looper.prepare()完成 Looper 的初始化

走进 Looper 类中可以看到,myLooper()方法是 Looper 类的静态方法,其只是单纯地从 sThreadLocal 变量中取值并返回而已。sThreadLocal 又是通过 prepare(boolean) 方法来进行初始化赋值的,且只能赋值一次,重复调用将抛出异常

我们知道,ThreadLocal 的特性就是可以为不同的线程分别维护单独的一个变量实例,所以,不同的线程就会分别对应着不同的 Looper 对象,是一一对应的关系

  1. @UnsupportedAppUsage
  2. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  3. /**
  4. * Return the Looper object associated with the current thread. Returns
  5. * null if the calling thread is not associated with a Looper.
  6. */
  7. public static @Nullable Looper myLooper() {
  8. return sThreadLocal.get();
  9. }
  10. /** Initialize the current thread as a looper.
  11. * This gives you a chance to create handlers that then reference
  12. * this looper, before actually starting the loop. Be sure to call
  13. * {@link #loop()} after calling this method, and end it by calling
  14. * {@link #quit()}.
  15. */
  16. public static void prepare() {
  17. prepare(true);
  18. }
  19. private static void prepare(boolean quitAllowed) {
  20. if (sThreadLocal.get() != null) {
  21. //只允许赋值一次
  22. //如果重复赋值则抛出异常
  23. throw new RuntimeException("Only one Looper may be created per thread");
  24. }
  25. sThreadLocal.set(new Looper(quitAllowed));
  26. }

此外,Looper 类的构造函数也是私有的,会初始化两个常量值:mQueue 和 mThread,这说明了 Looper 对于 MessageQueue 和 Thread 都是一一对应的关系,关联之后不能改变

  1. @UnsupportedAppUsage
  2. final MessageQueue mQueue;
  3. final Thread mThread;
  4. private Looper(boolean quitAllowed) {
  5. mQueue = new MessageQueue(quitAllowed);
  6. mThread = Thread.currentThread();
  7. }

在日常开发中,我们在通过 Handler 来执行 UI 刷新操作时,经常使用的是 Handler 的无参构造函数,那么此时肯定就是使用了和主线程关联的 Looper 对象,对应 Looper 类中的静态变量 sMainLooper

  1. @UnsupportedAppUsage
  2. private static Looper sMainLooper; // guarded by Looper.class
  3. //被标记为废弃的原因是因为 sMainLooper 会交由 Android 系统自动来完成初始化,外部不应该主动来初始化
  4. @Deprecated
  5. public static void prepareMainLooper() {
  6. prepare(false);
  7. synchronized (Looper.class) {
  8. if (sMainLooper != null) {
  9. throw new IllegalStateException("The main Looper has already been prepared.");
  10. }
  11. sMainLooper = myLooper();
  12. }
  13. }
  14. /**
  15. * Returns the application's main looper, which lives in the main thread of the application.
  16. */
  17. public static Looper getMainLooper() {
  18. synchronized (Looper.class) {
  19. return sMainLooper;
  20. }
  21. }

prepareMainLooper()就用于为主线程初始化 Looper 对象,该方法又是由 ActivityThread 类的 main() 方法来调用的。该 main() 方法即 Java 程序的运行起始点,所以当应用启动时系统就自动为我们在主线程做好了 mainLooper 的初始化,而且已经调用了Looper.loop()方法开启了消息的循环处理,应用在使用过程中的各种交互逻辑(例如:屏幕的触摸事件、列表的滑动等)就都是在这个循环里完成分发的

正是因为 Android 系统已经自动完成了主线程 Looper 的初始化,所以我们在主线程中才可以直接使用 Handler 的无参构造函数来完成 UI 相关事件的处理

  1. public final class ActivityThread extends ClientTransactionHandler {
  2. public static void main(String[] args) {
  3. ···
  4. Looper.prepareMainLooper();
  5. ···
  6. Looper.loop();
  7. throw new RuntimeException("Main thread loop unexpectedly exited");
  8. }
  9. }

3、Handler 发送消息

Handler 用于发送消息的方法非常多,有十几个,其中大部分最终调用到的都是 sendMessageAtTime() 方法。uptimeMillis 即 Message 具体要执行的时间戳,如果该时间戳比当前时间大,那么就意味着要执行的是延迟任务。如果为 mQueue 为 null,就会打印异常信息并直接返回,因为 Message 是需要交由 MessageQueue 来处理的

  1. public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
  2. MessageQueue queue = mQueue;
  3. if (queue == null) {
  4. RuntimeException e = new RuntimeException(
  5. this + " sendMessageAtTime() called with no mQueue");
  6. Log.w("Looper", e.getMessage(), e);
  7. return false;
  8. }
  9. return enqueueMessage(queue, msg, uptimeMillis);
  10. }

需要注意 msg.target = this 这句代码,target 指向了发送消息的主体,即 Handler 对象本身,即由 Handler 对象发给 MessageQueue 的消息最后还是要交由 Handler 对象本身来处理

  1. private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
  2. long uptimeMillis) {
  3. msg.target = this;
  4. msg.workSourceUid = ThreadLocalWorkSource.getUid();
  5. if (mAsynchronous) {
  6. msg.setAsynchronous(true);
  7. }
  8. //将消息交由 MessageQueue 处理
  9. return queue.enqueueMessage(msg, uptimeMillis);
  10. }

4、MessageQueue

MessageQueue 通过 enqueueMessage 方法来接收消息

到此,一个按照时间戳大小进行排序的消息队列就完成了,后边要做的就是从消息队列中依次取出消息进行处理了

  1. boolean enqueueMessage(Message msg, long when) {
  2. if (msg.target == null) {
  3. throw new IllegalArgumentException("Message must have a target.");
  4. }
  5. synchronized (this) {
  6. ···
  7. msg.markInUse();
  8. msg.when = when;
  9. Message p = mMessages;
  10. //用于标记是否需要唤醒线程
  11. boolean needWake;
  12. //如果链表是空的,或者处于队头的消息的时间戳比 msg 要大,则将 msg 作为链表头部
  13. //when == 0 说明 Handler 调用的是 sendMessageAtFrontOfQueue 方法,直接将 msg 插到队列头部
  14. if (p == null || when == 0 || when < p.when) {
  15. // New head, wake up the event queue if blocked.
  16. msg.next = p;
  17. mMessages = msg;
  18. needWake = mBlocked;
  19. } else {
  20. //如果当前线程处于休眠状态 + 队头消息是屏障消息 + msg 是异步消息
  21. //那么就需要唤醒线程
  22. needWake = mBlocked && p.target == null && msg.isAsynchronous();
  23. Message prev;
  24. //从链表头向链表尾遍历,寻找链表中第一条时间戳比 msg 大的消息,将 msg 插到该消息的前面
  25. for (;;) {
  26. prev = p;
  27. p = p.next;
  28. if (p == null || when < p.when) {
  29. break;
  30. }
  31. if (needWake && p.isAsynchronous()) {
  32. //如果在 msg 之前队列中还有异步消息那么就不需要主动唤醒
  33. //因为已经设定唤醒时间了
  34. needWake = false;
  35. }
  36. }
  37. msg.next = p; // invariant: p == prev.next
  38. prev.next = msg;
  39. }
  40. // We can assume mPtr != 0 because mQuitting is false.
  41. if (needWake) {
  42. nativeWake(mPtr);
  43. }
  44. }
  45. return true;
  46. }

知道了 Message 是如何保存的了,再来看下 MessageQueue 是如何取出 Message 并回调给 Handler 的。在 MessageQueue 中读取消息的操作对应的是next() 方法。next() 方法内部开启了一个无限循环,如果消息队列中没有消息或者是队头消息还没到可以处理的时间,该方法就会导致 Loop 线程休眠挂起,直到条件满足后再重新遍历消息

  1. @UnsupportedAppUsage
  2. Message next() {
  3. ···
  4. for (;;) {
  5. if (nextPollTimeoutMillis != 0) {
  6. Binder.flushPendingCommands();
  7. }
  8. //将 Loop 线程休眠挂起
  9. nativePollOnce(ptr, nextPollTimeoutMillis);
  10. synchronized (this) {
  11. // Try to retrieve the next message. Return if found.
  12. final long now = SystemClock.uptimeMillis();
  13. Message prevMsg = null;
  14. Message msg = mMessages;
  15. if (msg != null && msg.target == null) {
  16. // Stalled by a barrier. Find the next asynchronous message in the queue.
  17. do {
  18. prevMsg = msg;
  19. msg = msg.next;
  20. } while (msg != null && !msg.isAsynchronous());
  21. }
  22. if (msg != null) {
  23. if (now < msg.when) {
  24. //队头消息还未到处理时间,计算需要等待的时间
  25. // Next message is not ready. Set a timeout to wake up when it is ready.
  26. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
  27. } else {
  28. // Got a message.
  29. mBlocked = false;
  30. if (prevMsg != null) {
  31. prevMsg.next = msg.next;
  32. } else {
  33. mMessages = msg.next;
  34. }
  35. msg.next = null;
  36. if (DEBUG) Log.v(TAG, "Returning message: " + msg);
  37. msg.markInUse();
  38. return msg;
  39. }
  40. } else {
  41. // No more messages.
  42. nextPollTimeoutMillis = -1;
  43. }
  44. ···
  45. }
  46. ···
  47. }
  48. ···
  49. }
  50. }

next() 方法又是通过 Looper 类的 loop() 方法来循环调用的,loop() 方法内也是一个无限循环,唯一跳出循环的条件就是 queue.next()方法返回为 null。因为 next() 方法可能会触发阻塞操作,所以没有消息需要处理时也会导致 loop() 方法被阻塞着,而当 MessageQueue 有了新的消息,Looper 就会及时地处理这条消息并调用 msg.target.dispatchMessage(msg) 方法将消息回传给 Handler 进行处理

  1. /**
  2. * Run the message queue in this thread. Be sure to call
  3. * {@link #quit()} to end the loop.
  4. */
  5. public static void loop() {
  6. final Looper me = myLooper();
  7. if (me == null) {
  8. throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
  9. }
  10. ···
  11. for (;;) {
  12. Message msg = queue.next(); // might block
  13. if (msg == null) {
  14. // No message indicates that the message queue is quitting.
  15. return;
  16. }
  17. ···
  18. msg.target.dispatchMessage(msg);
  19. ···
  20. }
  21. }

Handler 的dispatchMessage方法就是在向外部分发 Message 了。至此,Message 的整个分发流程就结束了

  1. /**
  2. * Handle system messages here.
  3. */
  4. public void dispatchMessage(@NonNull Message msg) {
  5. if (msg.callback != null) {
  6. handleCallback(msg);
  7. } else {
  8. if (mCallback != null) {
  9. if (mCallback.handleMessage(msg)) {
  10. return;
  11. }
  12. }
  13. handleMessage(msg);
  14. }
  15. }

5、消息屏障

Handler的Message种类分为3种:

同步消息

我们通常使用的都是同步消息

  1. Handler mHandler = new Handler();
  2. mHandler.sendMessage();
  3. mHandler.post()
异步消息

Handler 的构造函数中的async参数就用于控制发送的 Message 是否属于异步消息

  1. public class Handler {
  2. final boolean mAsynchronous;
  3. public Handler(boolean async) {
  4. this(null, async);
  5. }
  6. public Handler(Callback callback, boolean async) {
  7. ...
  8. }
  9. public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
  10. ···
  11. mAsynchronous = async;
  12. }
  13. private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
  14. long uptimeMillis) {
  15. msg.target = this;
  16. msg.workSourceUid = ThreadLocalWorkSource.getUid();
  17. if (mAsynchronous) {
  18. //设为异步消息
  19. msg.setAsynchronous(true);
  20. }
  21. return queue.enqueueMessage(msg, uptimeMillis);
  22. }
  23. }

当然,也可以直接调用Message#setAsynchronous(true)。

屏障消息

屏障消息又称为同步屏障,屏障消息就是在消息队列中插入一个屏障,在屏障之后的所有同步消息都会被挡着,不能被处理。
屏障消息就是为了确保异步消息的优先级,设置了屏障后,只能处理其后的异步消息,同步消息会被挡住,除非撤销屏障。

插入消息屏障

同步屏只能通过MessageQueue#postSyncBarrier来插入到消息队列中,这个系统内部方法,我们是调用不到的:

  1. private int postSyncBarrier(long when) {
  2. synchronized (this) {
  3. final int token = mNextBarrierToken++;
  4. //1、屏障消息和普通消息的区别是屏障消息没有tartget。
  5. final Message msg = Message.obtain();
  6. msg.markInUse();
  7. msg.when = when;
  8. msg.arg1 = token;
  9. Message prev = null;
  10. Message p = mMessages;
  11. //2、根据时间顺序将屏障插入到消息链表中适当的位置
  12. if (when != 0) {
  13. while (p != null && p.when <= when) {
  14. prev = p;
  15. p = p.next;
  16. }
  17. }
  18. if (prev != null) { // invariant: p == prev.next
  19. msg.next = p;
  20. prev.next = msg;
  21. } else {
  22. msg.next = p;
  23. mMessages = msg;
  24. }
  25. //3、返回一个序号,通过这个序号可以撤销屏障
  26. return token;
  27. }
  28. }
读取消息屏障

MessageQueue 在取队头消息的时候,如果判断到队头消息就是屏障消息的话,那么就会向后遍历找到第一条异步消息优先进行处理

  1. @UnsupportedAppUsage
  2. Message next() {
  3. ···
  4. for (;;) {
  5. if (nextPollTimeoutMillis != 0) {
  6. Binder.flushPendingCommands();
  7. }
  8. nativePollOnce(ptr, nextPollTimeoutMillis);
  9. synchronized (this) {
  10. // Try to retrieve the next message. Return if found.
  11. final long now = SystemClock.uptimeMillis();
  12. Message prevMsg = null;
  13. Message msg = mMessages;
  14. if (msg != null && msg.target == null) { //target 为 null 即属于屏障消息
  15. // Stalled by a barrier. Find the next asynchronous message in the queue.
  16. //循环遍历,找到屏障消息后面的第一条异步消息进行处理
  17. do {
  18. prevMsg = msg;
  19. msg = msg.next;
  20. } while (msg != null && !msg.isAsynchronous());
  21. }
  22. ···
  23. }
  24. ···
  25. }
  26. }
移除消息屏障

同步消息要想执行,必须先移除消息屏障,需要调用MessageQueue#removeSyncBarrier

  1. public void removeSyncBarrier(int token) {
  2. // Remove a sync barrier token from the queue.
  3. // If the queue is no longer stalled by a barrier then wake it.
  4. synchronized (this) {
  5. Message prev = null;
  6. Message p = mMessages;
  7. while (p != null && (p.target != null || p.arg1 != token)) {
  8. prev = p;
  9. p = p.next;
  10. }
  11. if (p == null) {
  12. throw new IllegalStateException("The specified message queue synchronization "
  13. + " barrier token has not been posted or has already been removed.");
  14. }
  15. final boolean needWake;
  16. if (prev != null) {
  17. prev.next = p.next;
  18. needWake = false;
  19. } else {
  20. mMessages = p.next;
  21. needWake = mMessages == null || mMessages.target != null;
  22. }
  23. p.recycleUnchecked();
  24. // If the loop is quitting then it is already awake.
  25. // We can assume mPtr != 0 when mQuitting is false.
  26. if (needWake && !mQuitting) {
  27. nativeWake(mPtr);
  28. }
  29. }
  30. }
同步屏障使用场景

Android 系统中的 UI 更新相关的消息都是异步消息,确保优先执行

比如,在 View 更新时,draw、requestLayout、invalidate 等很多地方都调用了ViewRootImpl#scheduleTraversals(),如下:

  1. //ViewRootImpl.java
  2. void scheduleTraversals() {
  3. if (!mTraversalScheduled) {
  4. mTraversalScheduled = true;
  5. //开启同步屏障
  6. mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
  7. //发送异步消息
  8. mChoreographer.postCallback(
  9. Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
  10. if (!mUnbufferedInputDispatch) {
  11. scheduleConsumeBatchedInput();
  12. }
  13. notifyRendererOfFramePending();
  14. pokeDrawLockIfNeeded();
  15. }
  16. }

mHandler.getLooper().getQueue().postSyncBarrier()开启了同步屏障,然后发送了异步消息

  1. void doTraversal() {
  2. if (mTraversalScheduled) {
  3. mTraversalScheduled = false;
  4. // 移除同步屏障
  5. mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
  6. if (mProfile) {
  7. Debug.startMethodTracing("ViewAncestor");
  8. }
  9. performTraversals();
  10. if (mProfile) {
  11. Debug.stopMethodTracing();
  12. mProfile = false;
  13. }
  14. }
  15. }

mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);移除了同步屏障

6、退出 Looper 循环

Looper 类本身做了方法限制,除了主线程外,子线程关联的 MessageQueue 都支持退出 Loop 循环,即 quitAllowed 只有主线程才能是 false

  1. public final class Looper {
  2. private Looper(boolean quitAllowed) {
  3. mQueue = new MessageQueue(quitAllowed);
  4. mThread = Thread.currentThread();
  5. }
  6. public void quit() {
  7. mQueue.quit(false);
  8. }
  9. public void quitSafely() {
  10. mQueue.quit(true);
  11. }
  12. }

MessageQueue 支持两种方式来退出 Loop:

  1. void quit(boolean safe) {
  2. if (!mQuitAllowed) {
  3. //MessageQueue 设置了不允许退出循环,直接抛出异常
  4. throw new IllegalStateException("Main thread not allowed to quit.");
  5. }
  6. synchronized (this) {
  7. if (mQuitting) {
  8. //避免重复调用
  9. return;
  10. }
  11. mQuitting = true;
  12. if (safe) {
  13. //只移除所有尚未执行的消息,不移除时间戳等于当前时间的消息
  14. removeAllFutureMessagesLocked();
  15. } else {
  16. //移除所有消息
  17. removeAllMessagesLocked();
  18. }
  19. // We can assume mPtr != 0 because mQuitting was previously false.
  20. nativeWake(mPtr);
  21. }
  22. }

mQuitting会被置为true,然后在enqueueMessage和next都会使用到这个变量:

  1. boolean enqueueMessage(Message msg, long when) {
  2. ...
  3. synchronized (this) {
  4. if (mQuitting) {
  5. IllegalStateException e = new IllegalStateException(
  6. msg.target + " sending message to a Handler on a dead thread");
  7. Log.w(TAG, e.getMessage(), e);
  8. msg.recycle();
  9. return false;
  10. }
  11. ...
  12. }
  1. Message next() {
  2. ...
  3. synchronized (this) {
  4. if (mQuitting) {
  5. dispose();
  6. return null;
  7. }
  8. }
  9. }

MessagQueue退出了,但是我们知道Looper也是一个死循环,它是怎么退出的呢?
注意这里next方法直接会返回null,我们来看loop方法:

  1. public static void loop() {
  2. ...
  3. for (;;) {
  4. Message msg = queue.next(); // might block
  5. if (msg == null) {
  6. // No message indicates that the message queue is quitting.
  7. return;
  8. }
  9. ...
  10. }
  11. }

当得到的Message为null的时候,就直接退出了

7、IdleHandler

IdleHandler 是 MessageQueue 的一个内部接口,可以用于在 Loop 线程处于空闲状态的时候执行一些优先级不高的操作

  1. public static interface IdleHandler {
  2. boolean queueIdle();
  3. }

MessageQueue 在获取队头消息时,如果发现当前没有需要执行的 Message 的话,那么就会去遍历 mIdleHandlers,依次执行 IdleHandler

  1. private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
  2. @UnsupportedAppUsage
  3. Message next() {
  4. ···
  5. int pendingIdleHandlerCount = -1; // -1 only during first iteration
  6. int nextPollTimeoutMillis = 0;
  7. for (;;) {
  8. ···
  9. synchronized (this) {
  10. ···
  11. //如果队头消息 mMessages 为 null 或者 mMessages 需要延迟处理
  12. //那么就来执行 IdleHandler
  13. if (pendingIdleHandlerCount < 0
  14. && (mMessages == null || now < mMessages.when)) {
  15. pendingIdleHandlerCount = mIdleHandlers.size();
  16. }
  17. if (pendingIdleHandlerCount <= 0) {
  18. // No idle handlers to run. Loop and wait some more.
  19. mBlocked = true;
  20. continue;
  21. }
  22. if (mPendingIdleHandlers == null) {
  23. mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
  24. }
  25. mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
  26. }
  27. for (int i = 0; i < pendingIdleHandlerCount; i++) {
  28. final IdleHandler idler = mPendingIdleHandlers[i];
  29. mPendingIdleHandlers[i] = null; // release the reference to the handler
  30. boolean keep = false;
  31. try {
  32. //执行 IdleHandler
  33. //如果返回 false 的话说明之后不再需要执行,那就将其移除
  34. keep = idler.queueIdle();
  35. } catch (Throwable t) {
  36. Log.wtf(TAG, "IdleHandler threw exception", t);
  37. }
  38. if (!keep) {
  39. synchronized (this) {
  40. mIdleHandlers.remove(idler);
  41. }
  42. }
  43. }
  44. ···
  45. }
  46. }
应用场景

Android里面有一个场景:

当从一个Activity启动另一个Activity时,Ams要先调用当前Activity的onPause(),然后再启动目标Activity,目标Activity启动后,要把原Activity完全覆盖掉,按照Activity的生命周期管理,原Activity要调用onStop(),但它是在什么时候调用的呢,就是在IdleHandler中调用的。为什么这样做呢,因为新Activity的显示非常重要,要保证它的优先处理,旧Activity要销毁了,已经不显示UI界面了,那就等到UI线程处于空闲期再处理。

另一个场景:
例如,ActivityThread 就向主线程 MessageQueue 添加了一个 GcIdler,用于在主线程空闲时尝试去执行 GC 操作

  1. public final class ActivityThread extends ClientTransactionHandler {
  2. @UnsupportedAppUsage
  3. void scheduleGcIdler() {
  4. if (!mGcIdlerScheduled) {
  5. mGcIdlerScheduled = true;
  6. //添加 IdleHandler
  7. Looper.myQueue().addIdleHandler(mGcIdler);
  8. }
  9. mH.removeMessages(H.GC_WHEN_IDLE);
  10. }
  11. final class GcIdler implements MessageQueue.IdleHandler {
  12. @Override
  13. public final boolean queueIdle() {
  14. //尝试 GC
  15. doGcIfNeeded();
  16. purgePendingResources();
  17. return false;
  18. }
  19. }
  20. }

自己App的场景

Android应用运行启动之后,一般要进行全局初始化、资源加载、UI显示等一系列的操作,显然此时会出现CPU使用一个高峰期,如果这些任务不加区分,一股脑的全部运行起来,势必影响到UI的显示。因此,可以对此进行流程优化,全力把保障UI线程的运行,把初始化、资源加载分为两部分,一部分是UI界面显示必需的,另一部分和初始化界面不相关的,在应用启动阶段只运行和UI相关的部分,其余部分等到高峰期过去之后再运行。

  1. Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
  2. @Override public boolean queueIdle() {
  3. initInBackground(); //后台运行的初始化任务在UI处于空闲时运行
  4. return false;
  5. }
  6. });

8、做一个总结

再来总结下以上的所有内容

  1. 每个 Handler 都会和一个 Looper 实例关联在一起,可以在初始化 Handler 时通过构造函数主动传入实例,否则就会默认使用和当前线程关联的 Looper 对象
  2. 每个 Looper 都会和一个 MessageQueue 实例关联在一起,每个线程都需要通过调用 Looper.prepare()方法来初始化本线程独有的 Looper 实例,并通过调用Looper.loop()方法来使得本线程循环向 MessageQueue 取出消息并执行。Android 系统默认会为每个应用初始化和主线程关联的 Looper 对象,并且默认就开启了 loop 循环来处理主线程消息
  3. MessageQueue 按照链表结构来保存 Message,执行时间早(即时间戳小)的 Message 会排在链表的头部,Looper 会循环从链表中取出 Message 并回调给 Handler,取值的过程可能会包含阻塞操作
  4. Message、Handler、Looper、MessageQueue 这四者就构成了一个生产者和消费者模式。Message 相当于产品,MessageQueue 相当于传输管道,Handler 相当于生产者,Looper 相当于消费者
  5. Handler 对于 Looper、Handler 对于 MessageQueue、Looper 对于 MessageQueue、Looper 对于 Thread ,这几个之间都是一一对应的关系,在关联后无法更改,但 Looper 对于 Handler、MessageQueue 对于 Handler 可以是一对多的关系
  6. Handler 能用于更新 UI 包含了一个隐性的前提条件:Handler 与主线程 Looper 关联在了一起。在主线程中初始化的 Handler 会默认与主线程 Looper 关联在一起,所以其 handleMessage(Message msg) 方法就会由主线程来调用。在子线程初始化的 Handler 如果也想执行 UI 更新操作的话,则需要主动获取 mainLooper 来初始化 Handler
  7. 对于我们自己在子线程中创建的 Looper,当不再需要的时候我们应该主动退出循环,否则子线程将一直无法得到释放。对于主线程 Loop 我们则不应该去主动退出,否则将导致应用崩溃
  8. 我们可以通过向 MessageQueue 添加 IdleHandler 的方式,来实现在 Loop 线程处于空闲状态的时候执行一些优先级不高的任务。例如,假设我们有个需求是希望当主线程完成界面绘制等事件后再执行一些 UI 操作,那么就可以通过 IdleHandler 来实现,这可以避免拖慢用户看到首屏页面的速度

三、Handler 在系统中的应用

1、HandlerThread

HandlerThread 是 Android SDK 中和 Handler 在同个包下的一个类,从其名字就可以看出来它是一个线程,而且使用到了 Handler

其用法类似于以下代码。通过 HandlerThread 内部的 Looper 对象来初始化 Handler,同时在 Handler 中声明需要执行的耗时任务,主线程通过向 Handler 发送消息来触发 HandlerThread 去执行耗时任务

  1. class MainActivity : AppCompatActivity() {
  2. private val handlerThread = HandlerThread("I am HandlerThread")
  3. private val handler by lazy {
  4. object : Handler(handlerThread.looper) {
  5. override fun handleMessage(msg: Message) {
  6. Thread.sleep(2000)
  7. Log.e("MainActivity", "这里是子线程,可以用来执行耗时任务:" + Thread.currentThread().name)
  8. }
  9. }
  10. }
  11. override fun onCreate(savedInstanceState: Bundle?) {
  12. super.onCreate(savedInstanceState)
  13. setContentView(R.layout.activity_main)
  14. btn_test.setOnClickListener {
  15. handler.sendEmptyMessage(1)
  16. }
  17. handlerThread.start()
  18. }
  19. }

HandlerThread 的源码还是挺简单的,只有一百多行

HandlerThread 是 Thread 的子类,其作用就是为了用来执行耗时任务,其 run()方法会自动为自己创建一个 Looper 对象并保存到 mLooper,之后就主动开启消息循环,这样 HandlerThread 就会来循环处理 Message 了

  1. public class HandlerThread extends Thread {
  2. //线程优先级
  3. int mPriority;
  4. //线程ID
  5. int mTid = -1;
  6. //当前线程持有的 Looper 对象
  7. Looper mLooper;
  8. private @Nullable Handler mHandler;
  9. public HandlerThread(String name) {
  10. super(name);
  11. mPriority = Process.THREAD_PRIORITY_DEFAULT;
  12. }
  13. public HandlerThread(String name, int priority) {
  14. super(name);
  15. mPriority = priority;
  16. }
  17. @Override
  18. public void run() {
  19. mTid = Process.myTid();
  20. //触发当前线程创建 Looper 对象
  21. Looper.prepare();
  22. synchronized (this) {
  23. //获取 Looper 对象
  24. mLooper = Looper.myLooper();
  25. //唤醒所有处于等待状态的线程
  26. notifyAll();
  27. }
  28. //设置线程优先级
  29. Process.setThreadPriority(mPriority);
  30. onLooperPrepared();
  31. //开启消息循环
  32. Looper.loop();
  33. mTid = -1;
  34. }
  35. }

此外,HandlerThread 还包含一个getLooper()方法用于获取 Looper。当我们在外部调用handlerThread.start()启动线程后,由于其run()方法的执行时机依然是不确定的,所以 getLooper()方法就必须等到 Looper 初始化完毕后才能返回,否则就会由于wait()方法而一直阻塞等待。当run()方法初始化 Looper 完成后,就会调用notifyAll()来唤醒所有处于等待状态的线程。所以外部在使用 HandlerThread 前就记得必须先调用 start() 方法来启动 HandlerThread

  1. //获取与 HandlerThread 关联的 Looper 对象
  2. //因为 getLooper() 可能先于 run() 被执行
  3. //所以当 mLooper 为 null 时调用者线程就需要阻塞等待 Looper 对象创建完毕
  4. public Looper getLooper() {
  5. if (!isAlive()) {
  6. return null;
  7. }
  8. // If the thread has been started, wait until the looper has been created.
  9. synchronized (this) {
  10. while (isAlive() && mLooper == null) {
  11. try {
  12. wait();
  13. } catch (InterruptedException e) {
  14. }
  15. }
  16. }
  17. return mLooper;
  18. }

HandlerThread 起到的作用就是方便了主线程和子线程之间的交互,主线程可以直接通过 Handler 来声明耗时任务并交由子线程来执行。使用 HandlerThread 也方便在多个线程间共享,主线程和其它子线程都可以向 HandlerThread 下发任务,且 HandlerThread 可以保证多个任务执行时的有序性

2、IntentService

IntentService 是系统提供的 Service 子类,用于在后台串行执行耗时任务,在处理完所有任务后会自动停止,不必来手动调用 stopSelf() 方法。而且由于IntentService 是四大组件之一,拥有较高的优先级,不易被系统杀死,因此适合用于执行一些高优先级的异步任务

Google 官方以前也推荐开发者使用 IntentService,但是在 Android 11 中已经被标记为废弃状态了,但这也不妨碍我们来了解下其实现原理

IntentService 内部依靠 HandlerThread 来实现,其 onCreate()方法会创建一个 HandlerThread,拿到 Looper 对象来初始化 ServiceHandler。ServiceHandler 会将其接受到的每个 Message 都转交由抽象方法 onHandleIntent来处理,子类就通过实现该方法来声明耗时任务

  1. public abstract class IntentService extends Service {
  2. private volatile Looper mServiceLooper;
  3. @UnsupportedAppUsage
  4. private volatile ServiceHandler mServiceHandler;
  5. private final class ServiceHandler extends Handler {
  6. public ServiceHandler(Looper looper) {
  7. super(looper);
  8. }
  9. @Override
  10. public void handleMessage(Message msg) {
  11. onHandleIntent((Intent)msg.obj);
  12. stopSelf(msg.arg1);
  13. }
  14. }
  15. @Override
  16. public void onCreate() {
  17. super.onCreate();
  18. HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
  19. //触发 HandlerThread 创建 Looper 对象
  20. thread.start();
  21. //获取 Looper 对象,构建可以向 HandlerThread 发送 Message 的 Handler
  22. mServiceLooper = thread.getLooper();
  23. mServiceHandler = new ServiceHandler(mServiceLooper);
  24. }
  25. @WorkerThread
  26. protected abstract void onHandleIntent(@Nullable Intent intent);
  27. }

每次 start IntentService 时,onStart()方法就会被调用,将 intentstartId 包装为一个 Message 对象后发送给mServiceHandler。需要特别注意的是 startId 这个参数,它用于唯一标识每次对 IntentService 发起的任务请求,每次回调 onStart() 方法时,startId 的值都是自动递增的。IntentService 不应该在处理完一个 Message 之后就立即停止 IntentService,因为此时 MessageQueue 中可能还有待处理的任务还未取出来,所以如果当调用 stopSelf(int)方法时传入的参数不等于当前最新的 startId 值的话,那么stopSelf(int) 方法就不会导致 IntentService 被停止,从而避免了将尚未处理的 Message 给遗漏了

  1. @Override
  2. public void onStart(@Nullable Intent intent, int startId) {
  3. Message msg = mServiceHandler.obtainMessage();
  4. msg.arg1 = startId;
  5. msg.obj = intent;
  6. mServiceHandler.sendMessage(msg);
  7. }
  8. @Override
  9. public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
  10. onStart(intent, startId);
  11. return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
  12. }

四、Handler 在三方库中的应用

1、EventBus

EventBus 的 Github 上有这么一句介绍:EventBus is a publish/subscribe event bus for Android and Java. 这说明了 EventBus 是普遍适用于 Java 环境的,只是对 Android 系统做了特殊的平台支持而已。EventBus 的四种消息发送策略包含了ThreadMode.MAIN 用于指定在主线程进行消息回调,其内部就是通过 Handler 来实现的

EventBusBuilder 会去尝试获取 MainLooper,如果拿得到的话就可以用来初始化 HandlerPoster,从而实现主线程回调

  1. MainThreadSupport getMainThreadSupport() {
  2. if (mainThreadSupport != null) {
  3. return mainThreadSupport;
  4. } else if (AndroidLogger.isAndroidLogAvailable()) {
  5. Object looperOrNull = getAndroidMainLooperOrNull();
  6. return looperOrNull == null ? null :
  7. new MainThreadSupport.AndroidHandlerMainThreadSupport((Looper) looperOrNull);
  8. } else {
  9. return null;
  10. }
  11. }
  12. static Object getAndroidMainLooperOrNull() {
  13. try {
  14. return Looper.getMainLooper();
  15. } catch (RuntimeException e) {
  16. // Not really a functional Android (e.g. "Stub!" maven dependencies)
  17. return null;
  18. }
  19. }
  1. public class HandlerPoster extends Handler implements Poster {
  2. protected HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
  3. super(looper);
  4. ···
  5. }
  6. ···
  7. @Override
  8. public void handleMessage(Message msg) {
  9. ···
  10. }
  11. }

2、Retrofit

和 EventBus 一样,Retrofit 的内部实现也不需要依赖于 Android 平台,而是可以用于任意的 Java 客户端,Retrofit 只是对 Android 平台进行了特殊实现而已

在构建 Retrofit 对象的时候,我们可以选择传递一个 Platform 对象用于标记调用方所处的平台

  1. public static final class Builder {
  2. private final Platform platform;
  3. Builder(Platform platform) {
  4. this.platform = platform;
  5. }
  6. ···
  7. }

Platform 类只具有一个唯一子类,即 Android 类。其主要逻辑就是重写了父类的 defaultCallbackExecutor()方法,通过 Handler 来实现在主线程回调网络请求结果

  1. static final class Android extends Platform {
  2. @Override
  3. public Executor defaultCallbackExecutor() {
  4. return new MainThreadExecutor();
  5. }
  6. ···
  7. static final class MainThreadExecutor implements Executor {
  8. private final Handler handler = new Handler(Looper.getMainLooper());
  9. @Override
  10. public void execute(Runnable r) {
  11. handler.post(r);
  12. }
  13. }
  14. }

五、面试环节

1、Handler、Looper、MessageQueue、Thread 的对应关系

首先,Looper 中的 MessageQueue 和 Thread 两个字段都属于常量,且 Looper 实例是存在 ThreadLocal 中,这说明了 Looper 和 MessageQueue 之间是一对一应的关系,且一个 Thread 在其整个生命周期内都只会关联到同一个 Looper 对象和同一个 MessageQueue 对象

  1. public final class Looper {
  2. final MessageQueue mQueue;
  3. final Thread mThread;
  4. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  5. private Looper(boolean quitAllowed) {
  6. mQueue = new MessageQueue(quitAllowed);
  7. mThread = Thread.currentThread();
  8. }
  9. }

Handler 中的 Looper 和 MessageQueue 两个字段也都属于常量,说明 Handler 对于 Looper 和 MessageQueue 都是一对一的关系。但是 Looper 和 MessageQueue 对于 Handler 却可以是一对多的关系,例如,多个子线程内声明的 Handler 都可以关联到 mainLooper

  1. public class Handler {
  2. @UnsupportedAppUsage
  3. final Looper mLooper;
  4. final MessageQueue mQueue;
  5. }

2、Handler 的同步机制

MessageQueue 在保存 Message 的时候,enqueueMessage方法内部已经加上了同步锁,从而避免了多个线程同时发送消息导致竞态问题。此外,next()方法内部也加上了同步锁,所以也保障了 Looper 分发 Message 的有序性。最重要的一点是,Looper 总是由一个特定的线程来执行遍历,所以在消费 Message 的时候也不存在竞态

  1. boolean enqueueMessage(Message msg, long when) {
  2. if (msg.target == null) {
  3. throw new IllegalArgumentException("Message must have a target.");
  4. }
  5. synchronized (this) {
  6. ···
  7. }
  8. return true;
  9. }
  10. @UnsupportedAppUsage
  11. Message next() {
  12. ···
  13. for (;;) {
  14. if (nextPollTimeoutMillis != 0) {
  15. Binder.flushPendingCommands();
  16. }
  17. nativePollOnce(ptr, nextPollTimeoutMillis);
  18. synchronized (this) {
  19. ···
  20. }
  21. ···
  22. }
  23. }

3、Handler 如何发送同步消息

4、Handler 如何避免内存泄漏

当退出 Activity 时,如果 Handler 中还保存着待处理的延时消息的话,那么就会导致内存泄漏,此时可以通过调用Handler.removeCallbacksAndMessages(null)来移除所有待处理的 Message

该方法会将消息队列中所有 Message.obj 等于 token 的 Message 均给移除掉,如果 token 为 null 的话则会移除所有 Message

  1. public final void removeCallbacksAndMessages(@Nullable Object token) {
  2. mQueue.removeCallbacksAndMessages(this, token);
  3. }

注意把this传进去了,所以只会删除与本Handler相关的所有Message。

5、Message 如何复用

因为 Android 系统本身就存在很多事件需要交由 Message 来交付给 mainLooper,所以 Message 的创建是很频繁的。为了减少 Message 频繁重复创建的情况,Message 提供了 MessagePool 用于实现 Message 的缓存复用,以此来优化内存使用

当 Looper 消费了 Message 后会调用recycleUnchecked()方法将 Message 进行回收,在清除了各项资源后会缓存到 sPool 变量上,同时将之前缓存的 Message 置为下一个节点 next,通过这种链表结构来缓存最多 50 个Message。这里使用到的是享元设计模式

obtain()方法则会判断当前是否有可用的缓存,有的话则将 sPool 从链表中移除后返回,否则就返回一个新的 Message 实例。所以我们在发送消息的时候应该尽量通过调用Message.obtain()或者Handler.obtainMessage()方法来获取 Message 实例

  1. public final class Message implements Parcelable {
  2. /** @hide */
  3. public static final Object sPoolSync = new Object();
  4. private static Message sPool;
  5. private static int sPoolSize = 0;
  6. private static final int MAX_POOL_SIZE = 50;
  7. public static Message obtain() {
  8. synchronized (sPoolSync) {
  9. if (sPool != null) {
  10. Message m = sPool;
  11. sPool = m.next;
  12. m.next = null;
  13. m.flags = 0; // clear in-use flag
  14. sPoolSize--;
  15. return m;
  16. }
  17. }
  18. return new Message();
  19. }
  20. @UnsupportedAppUsage
  21. void recycleUnchecked() {
  22. // Mark the message as in use while it remains in the recycled object pool.
  23. // Clear out all other details.
  24. flags = FLAG_IN_USE;
  25. what = 0;
  26. arg1 = 0;
  27. arg2 = 0;
  28. obj = null;
  29. replyTo = null;
  30. sendingUid = UID_NONE;
  31. workSourceUid = UID_NONE;
  32. when = 0;
  33. target = null;
  34. callback = null;
  35. data = null;
  36. synchronized (sPoolSync) {
  37. if (sPoolSize < MAX_POOL_SIZE) {
  38. next = sPool;
  39. sPool = this;
  40. sPoolSize++;
  41. }
  42. }
  43. }
  44. }

6、Message 复用机制存在的问题

由于 Message 采用了缓存复用机制,从而导致了一个 Message 失效问题。当 handleMessage 方法被回调后,Message 携带的所有参数都会被清空,而如果外部的 handleMessage方法是使用了异步线程来处理 Message 的话,那么异步线程只会得到一个空白的 Message

  1. val handler = object : Handler() {
  2. override fun handleMessage(msg: Message) {
  3. handleMessageAsync(msg)
  4. }
  5. }
  6. fun handleMessageAsync(msg: Message) {
  7. thread {
  8. //只会得到一个空白的 Message 对象
  9. println(msg.obj)
  10. }
  11. }

7、Message 如何提高优先级

Handler 包含一个 sendMessageAtFrontOfQueue方法可以用于提高 Message 的处理优先级。该方法为 Message 设定的时间戳是 0,使得 Message 可以直接插入到 MessageQueue 的头部,从而做到优先处理。但官方并不推荐使用这个方法,因为最极端的情况下可能会使得其它 Message 一直得不到处理或者其它意想不到的情况

  1. public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg) {
  2. MessageQueue queue = mQueue;
  3. if (queue == null) {
  4. RuntimeException e = new RuntimeException(
  5. this + " sendMessageAtTime() called with no mQueue");
  6. Log.w("Looper", e.getMessage(), e);
  7. return false;
  8. }
  9. return enqueueMessage(queue, msg, 0);
  10. }

8、检测 Looper 分发 Message 的效率

Looper 在进行 Loop 循环时,会通过 Observer 向外回调每个 Message 的回调事件。且如果设定了 slowDispatchThresholdMsslowDeliveryThresholdMs 这两个阈值的话,则会对 Message 的分发时机分发耗时进行监测,存在异常情况的话就会打印 Log。该机制可以用于实现应用性能监测,发现潜在的 Message 处理异常情况,但可惜监测方法被系统隐藏了

  1. public static void loop() {
  2. final Looper me = myLooper();
  3. ···
  4. for (;;) {
  5. Message msg = queue.next(); // might block
  6. ···
  7. //用于向外回调通知 Message 的分发事件
  8. final Observer observer = sObserver;
  9. final long traceTag = me.mTraceTag;
  10. //如果Looper分发Message的时间晚于预定时间且超出这个阈值,则认为Looper分发过慢
  11. long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
  12. //如果向外分发出去的Message的处理时间超出这个阈值,则认为外部处理过慢
  13. long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
  14. if (thresholdOverride > 0) {
  15. slowDispatchThresholdMs = thresholdOverride;
  16. slowDeliveryThresholdMs = thresholdOverride;
  17. }
  18. final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
  19. final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
  20. final boolean needStartTime = logSlowDelivery || logSlowDispatch;
  21. final boolean needEndTime = logSlowDispatch;
  22. if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
  23. Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
  24. }
  25. //开始分发 Message 的时间
  26. final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
  27. //Message 分发结束的时间
  28. final long dispatchEnd;
  29. Object token = null;
  30. if (observer != null) {
  31. //开始分发 Message
  32. token = observer.messageDispatchStarting();
  33. }
  34. long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
  35. try {
  36. msg.target.dispatchMessage(msg);
  37. if (observer != null) {
  38. //完成 Message 的分发,且没有抛出异常
  39. observer.messageDispatched(token, msg);
  40. }
  41. dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
  42. } catch (Exception exception) {
  43. if (observer != null) {
  44. //分发 Message 时抛出了异常
  45. observer.dispatchingThrewException(token, msg, exception);
  46. }
  47. throw exception;
  48. } finally {
  49. ThreadLocalWorkSource.restore(origWorkSource);
  50. if (traceTag != 0) {
  51. Trace.traceEnd(traceTag);
  52. }
  53. }
  54. if (logSlowDelivery) {
  55. if (slowDeliveryDetected) {
  56. if ((dispatchStart - msg.when) <= 10) {
  57. //如果 Message 的分发时间晚于预定时间,且间隔超出10毫秒,则认为属于延迟交付
  58. Slog.w(TAG, "Drained");
  59. slowDeliveryDetected = false;
  60. }
  61. } else {
  62. if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
  63. msg)) {
  64. // Once we write a slow delivery log, suppress until the queue drains.
  65. slowDeliveryDetected = true;
  66. }
  67. }
  68. }
  69. ···
  70. }
  71. }

9、主线程 Looper 在哪里创建

由 ActivityThread 类的 main() 方法来创建。该 main() 方法即 Java 程序的运行起始点,当应用启动时系统就自动为我们在主线程做好了 mainLooper 的初始化,而且已经调用了Looper.loop()方法开启了消息的循环处理,应用在使用过程中的各种交互逻辑(例如:屏幕的触摸事件、列表的滑动等)就都是在这个循环里完成分发的。正是因为 Android 系统已经自动完成了主线程 Looper 的初始化,所以我们在主线程中才可以直接使用 Handler 的无参构造函数来完成 UI 相关事件的处理

  1. public final class ActivityThread extends ClientTransactionHandler {
  2. public static void main(String[] args) {
  3. ···
  4. Looper.prepareMainLooper();
  5. ···
  6. Looper.loop();
  7. throw new RuntimeException("Main thread loop unexpectedly exited");
  8. }
  9. }

10、主线程 Looper 什么时候退出循环

当 ActivityThread 内部的 Handler 收到了 EXIT_APPLICATION 消息后,就会退出 Looper 循环

  1. public void handleMessage(Message msg) {
  2. switch (msg.what) {
  3. case EXIT_APPLICATION:
  4. if (mInitialApplication != null) {
  5. mInitialApplication.onTerminate();
  6. }
  7. Looper.myLooper().quit();
  8. break;
  9. }
  10. }

11、主线程 Looper.loop() 为什么不会导致 ANR

首先这两之间一点联系都没有,完全两码事:

准确的讲,主线程确实堵塞了,Looper实现了可阻塞的死循环。当没有消息的时候,主线程既不能退出,又不能无阻塞死循环执行,最后的办法只能是让他有消息的时候处理消息,没消息的时候进入阻塞状态。利用Linux的epoll+pipe机制,使得主线程在阻塞的时候,让出CPU资源,同时等待新消息。当我们对系统进行操作(包括各种滑动和点击)的时候,系统就会给主线程发送消息,这个时候就会唤醒主线程(执行onCreate,onResume等方法),当处理完这个消息,就会再次进入阻塞状态。这样系统就能做到随时响应用户的操作。真正的ANR绝不是Looper轮询消息导致的,而是处理消息过程中的问题。事件只会阻塞Looper,而Looper不会阻塞事件,当某个事件在主线程执行了耗时操作,影响了Looper轮询后面的消息,才会发生ANR。

这个问题在网上很常见,我第一次看到时就觉得这种问题很奇怪,主线程凭啥会 ANR?这个问题感觉本身就是特意为了来误导人

看以下例子。doSomeThing()方法是放在 for 循环这个死循环的后边,对于该方法来说,主线程的确是被阻塞住了,导致该方法一直无法得到执行。可是对于应用来说,应用在主线程内的所有操作其实都是被放在了 for 循环之内,一直有得到执行,是个死循环也无所谓,所以对于应用来说主线程并没有被阻塞,自然不会导致 ANR。此外,当 MessageQueue 中当前没有消息需要处理时,也会依靠 epoll 机制挂起主线程,避免了其一直占用 CPU 资源

  1. public static void main(String[] args) {
  2. for (; ; ) {
  3. //主线程执行....
  4. }
  5. doSomeThing();
  6. }

所以在 ActivityThread 的 main 方法中,在开启了消息循环之后,并没有声明什么有意义的代码。正常来说应用是不会退出 loop 循环的,如果能够跳出循环,也只会导致直接就抛出异常

  1. public static void main(String[] args) {
  2. ···
  3. Looper.prepareMainLooper();
  4. ···
  5. Looper.loop();
  6. throw new RuntimeException("Main thread loop unexpectedly exited");
  7. }

所以说,loop 循环本身不会导致 ANR,会出现 ANR 是因为在 loop 循环之内 Message 处理时间过长

我们写一个Button,然后给Button点击事件,内容就是sleep 10s,这个会发生ANR吗?

ANR 的原因是因为Looper对象MessageQueue队列中的事件没有能够得到及时执行,超过阀值就会ANR

12、子线程一定无法弹 Toast 吗

不一定,只能说是在子线程中无法直接弹出 Toast,但可以实现。因为 Toast 的构造函数中会要求拿到一个 Looper 对象,如果构造参数没有传入不为 null 的 Looper 实例的话,则尝试使用调用者线程关联的 Looper 对象,如果都获取不到的话则会抛出异常

  1. public Toast(Context context) {
  2. this(context, null);
  3. }
  4. public Toast(@NonNull Context context, @Nullable Looper looper) {
  5. mContext = context;
  6. mToken = new Binder();
  7. looper = getLooper(looper);
  8. mHandler = new Handler(looper);
  9. ···
  10. }
  11. private Looper getLooper(@Nullable Looper looper) {
  12. if (looper != null) {
  13. return looper;
  14. }
  15. //Looper.myLooper() 为 null 的话就会直接抛出异常
  16. return checkNotNull(Looper.myLooper(),
  17. "Can't toast on a thread that has not called Looper.prepare()");
  18. }

为了在子线程弹 Toast,就需要主动为子线程创建 Looper 对象及开启 loop 循环。但这种方法会导致子线程一直无法退出循环,需要通过Looper.myLooper().quit()来主动退出循环

  1. inner class TestThread : Thread() {
  2. override fun run() {
  3. Looper.prepare()
  4. Toast.makeText(
  5. this@MainActivity,
  6. "Hello: " + Thread.currentThread().name,
  7. Toast.LENGTH_SHORT
  8. ).show()
  9. Looper.loop()
  10. }
  11. }

13、子线程一定无法更新 UI?主线程就一定可以?

在子线程能够弹出 Toast 就已经说明了子线程也是可以更新 UI 的,Android 系统只是限制了必须在同个线程内进行 ViewRootImpl 的创建和更新这两个操作,而不是要求必须在主线程进行

如果使用不当的话,即使在主线程更新 UI 也可能会导致应用崩溃。例如,在子线程先通过 show+hide 来触发 ViewRootImpl 的创建,然后在主线程再来尝试显示该 Dialog,此时就会发现程序直接崩溃了

  1. class MainActivity : AppCompatActivity() {
  2. private lateinit var alertDialog: AlertDialog
  3. private val thread = object : Thread("hello") {
  4. override fun run() {
  5. Looper.prepare()
  6. Handler().post {
  7. alertDialog =
  8. AlertDialog.Builder(this@MainActivity).setMessage(Thread.currentThread().name)
  9. .create()
  10. alertDialog.show()
  11. alertDialog.hide()
  12. }
  13. Looper.loop()
  14. }
  15. }
  16. override fun onCreate(savedInstanceState: Bundle?) {
  17. super.onCreate(savedInstanceState)
  18. setContentView(R.layout.activity_main)
  19. btn_test.setOnClickListener {
  20. alertDialog.show()
  21. }
  22. thread.start()
  23. }
  24. }
  1. E/AndroidRuntime: FATAL EXCEPTION: main
  2. Process: github.leavesc.test, PID: 5243
  3. android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
  4. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6892)
  5. at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1048)
  6. at android.view.View.requestLayout(View.java:19781)
  7. at android.view.View.setFlags(View.java:11478)
  8. at android.view.View.setVisibility(View.java:8069)
  9. at android.app.Dialog.show(Dialog.java:293)

ViewRootImpl 在初始化的时候会将当前线程保存到 mThread,在后续进行 UI 更新的时候就会调用checkThread()方法进行线程检查,如果发现存在多线程调用则直接抛出以上的异常信息

  1. public final class ViewRootImpl implements ViewParent,
  2. View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks {
  3. final Thread mThread;
  4. public ViewRootImpl(Context context, Display display, IWindowSession session,
  5. boolean useSfChoreographer) {
  6. mThread = Thread.currentThread();
  7. ···
  8. }
  9. void checkThread() {
  10. if (mThread != Thread.currentThread()) {
  11. throw new CalledFromWrongThreadException(
  12. "Only the original thread that created a view hierarchy can touch its views.");
  13. }
  14. }
  15. }

13.1、子线程如何更新UI呢?

1、在 Activity#onResume() 及以前更新 View

参考:窗口机制,我们知道ViewRootImpl的创建是在onResume之后(ActivityThread#handleResumeActivity->WindowManager#addView->WindowManagerGlobal#addView->ew ViewRootImpl()->ViewRootImpl#setView()),所以这个时候才把ViewRootImpl设置为DecorView的parent,所有的更新UI界面的操作,在递归之后都是调用的ViewRootImpl,所以我们如果在onResume之前更新UI,由于ViewRootImpl还没有设置为DecorView的parent,所以不会走到ViewRootImpl,就不会引起崩溃了

  1. override fun onCreate(savedInstanceState: Bundle?) {
  2. super.onCreate(savedInstanceState)
  3. setContentView(R.layout.activity_main)
  4. thread { imageView.setBackgroundColor(Color.RED) }
  5. }
2、子线程初始化 ViewRootImpl
  1. button.setOnClickListener {
  2. thread {
  3. Looper.prepare()
  4. val imageView = ImageView(this)
  5. windowManager.addView(imageView, WindowManager.LayoutParams())
  6. imageView.setBackgroundColor(Color.RED)
  7. Looper.loop()
  8. }

注意要在 Looper.prepare() 之后调用 WindowManager#addView(),否则会报错

  1. java.lang.RuntimeException: Can't create handler inside thread Thread[xxxx] that has not called Looper.prepare()。

原因是 ViewRootImpl 初始化的时候会创建一个 Headler,并且是创建异步消息的Handler,而 Headler 初始化的时候会调用Looper#myLooper()。

  1. public class Handler {
  2. final boolean mAsynchronous;
  3. public Handler(boolean async) {
  4. this(null, async);
  5. }
  6. public Handler(Callback callback, boolean async) {
  7. ...
  8. }
  9. public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
  10. ···
  11. mAsynchronous = async;
  12. }
  13. private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
  14. long uptimeMillis) {
  15. msg.target = this;
  16. msg.workSourceUid = ThreadLocalWorkSource.getUid();
  17. if (mAsynchronous) {
  18. //设为异步消息
  19. msg.setAsynchronous(true);
  20. }
  21. return queue.enqueueMessage(msg, uptimeMillis);
  22. }
  23. }
3、SurfaceView 和 TextureView

这两个 View 是根红苗正用来子线程更新 View 的,SurfaceView 使用自带 Surface 去做画面渲染,TextureView 同样可以通过 TextureView#lockCanvas() 使用临时的 Surface,所以都不会触发 View#requestLayout()。

14、为什么 UI 体系要采用单线程模型

其实这很好理解,就是为了提高运行效率和降低实现难度。如果允许多线程并发访问 UI 的话,为了避免竞态,很多即使只是小范围的局部刷新操作(例如,TextView.setText)都势必需要加上同步锁,这无疑会加大 UI 刷新操作的“成本”,降低了整个应用的运行效率。而且会导致 Android 的 UI 体系在实现时就被迫需要对多线程环境进行“防御”,即使开发者一直是使用同个线程来更新 UI,这就加大了系统的实现难度

所以,最为简单高效的方式就是采用单线程模型来访问 UI

15、如何跨线程下发任务

通常情况下,两个线程之间的通信是比较麻烦的,需要做很多线程同步操作。而依靠 Looper 的特性,我们就可以用比较简单的方式来实现跨线程下发任务

看以下代码,从 TestThread 运行后弹出的线程名可以知道, Toast 是在 Thread_1 被弹出来的。如果将 Thread_2 想像成主线程的话,那么以下代码就相当于从主线程向子线程下发耗时任务了,这个实现思路就相当于 Android 提供的 HandlerThread 类

  1. inner class TestThread : Thread("Thread_1") {
  2. override fun run() {
  3. Looper.prepare()
  4. val looper = Looper.myLooper()
  5. object : Thread("Thread_2") {
  6. override fun run() {
  7. val handler = Handler(looper!!)
  8. handler.post {
  9. //输出结果是:Thread_1
  10. Toast.makeText(
  11. this@MainActivity,
  12. Thread.currentThread().name,
  13. Toast.LENGTH_SHORT
  14. ).show()
  15. }
  16. }
  17. }.start()
  18. Looper.loop()
  19. }
  20. }

16、如何判断当前是不是主线程

通过 Looper 来判断

  1. if (Looper.myLooper() == Looper.getMainLooper()) {
  2. //是主线程
  3. }
  4. if (Looper.getMainLooper().isCurrentThread){
  5. //是主线程
  6. }

17、如何全局捕获主线程异常

比较卧槽的一个做法就是通过嵌套 Loop 循环来实现。向主线程 Loop 发送 一个 Runnable,在 Runnable 里死循环执行 Loop 循环,这就会使得主线程消息队列中的所有任务都会被交由该 Runnable 来调用,只要加上 try catch 后就可以捕获主线程的任意异常了,做到主线程永不崩溃

  1. Handler(Looper.getMainLooper()).post {
  2. while (true) {
  3. try {
  4. Looper.loop()
  5. } catch (throwable: Throwable) {
  6. throwable.printStackTrace()
  7. Log.e("TAG", throwable.message ?: "")
  8. }
  9. }
  10. }

18、为什么不用 wait 而用 epoll 呢?

在 Android 2.2 及之前,使用 Java wait / notify 进行等待,在 2.3 以后,使用 epoll 机制,为了可以同时处理 native 侧的消息。

说起来 java 中的 wait / notify 也能实现阻塞等待消息的功能,在 Android 2.2 及以前,也确实是这样做的。
可以参考这个 commit https://www.androidos.net.cn/android/2.1_r2.1p2/xref/frameworks/base/core/java/android/os/MessageQueue.java
那为什么后面要改成使用 epoll 呢?通过看 commit 记录,是需要处理 native 侧的事件,所以只使用 java 的 wait / notify 就不够用了。
具体的改动就是这个 commit https://android.googlesource.com/platform/frameworks/base/+/fa9e7c05c7be6891a6cf85a11dc635a6e6853078%5E%21/#F0

  1. Sketch of Native input for MessageQueue / Looper / ViewRoot
  2. MessageQueue now uses a socket for internal signalling, and is prepared
  3. to also handle any number of event input pipes, once the plumbing is
  4. set up with ViewRoot / Looper to tell it about them as appropriate.

Change-Id: If9eda174a6c26887dc51b12b14b390e724e73ab3
不过这里最开始使用的还是 select,后面才改成 epoll。
具体可见这个 commit https://android.googlesource.com/platform/frameworks/base/+/46b9ac0ae2162309774a7478cd9d4e578747bfc2%5E%21/#F16

至于 select 和 epoll 的区别,这里也不细说了,大家可以在参考文章中一起看看。

19、View.post 和 Handler.post 的区别

一文读懂ViewPost的原理及缺陷

我们最常用的 Handler 功能就是 Handler.post,除此之外,还有 View.post 也经常会用到,那么这两个有什么区别呢?
我们先看下 View.post 的代码。

  1. // View.java
  2. public boolean post(Runnable action) {
  3. final AttachInfo attachInfo = mAttachInfo;
  4. if (attachInfo != null) {
  5. return attachInfo.mHandler.post(action);
  6. }
  7. // Postpone the runnable until we know on which thread it needs to run.
  8. // Assume that the runnable will be successfully placed after attach.
  9. getRunQueue().post(action);
  10. return true;
  11. }

通过代码来看:

那我们先看看这里的 AttachInfo 是什么。
这个就需要追溯到 ViewRootImpl 的流程里了,我们先看下面这段代码。

  1. // ViewRootImpl.java
  2. final ViewRootHandler mHandler = new ViewRootHandler();
  3. public ViewRootImpl(Context context, Display display) {
  4. // ...
  5. mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this,
  6. context);
  7. }
  8. private void performTraversals() {
  9. final View host = mView;
  10. // ...
  11. if (mFirst) {
  12. host.dispatchAttachedToWindow(mAttachInfo, 0);
  13. mFirst = false;
  14. }
  15. // ...
  16. }

代码写了一些关键部分,在 ViewRootImpl 构造函数里,创建了 mAttachInfo,然后在 performTraversals 里,如果 mFirst 为 true,则调用 host.dispatchAttachedToWindow,这里的 host 就是 DecorView,如果有读者朋友对这里不太清楚,可以看看前面【面试官带你学安卓-从View的绘制流程】说起这篇文章复习一下。

这里还有一个知识点就是 mAttachInfo 中的 mHandler 其实是 ViewRootImpl 内部的 ViewRootHandler。

然后就调用到了 DecorView.dispatchAttachedToWindow,其实就是 ViewGroup 的 dispatchAttachedToWindow,一般 ViewGroup 中相关的方法,都是去依次调用 child 的对应方法,这个也不例外,依次调用子 View 的 dispatchAttachedToWindow,把 AttachInfo 传进去,在 子 View 中给 mAttachInfo 赋值。

  1. // ViewGroup
  2. void dispatchAttachedToWindow(AttachInfo info, int visibility) {
  3. mGroupFlags |= FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
  4. super.dispatchAttachedToWindow(info, visibility);
  5. mGroupFlags &= ~FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
  6. final int count = mChildrenCount;
  7. final View[] children = mChildren;
  8. for (int i = 0; i < count; i++) {
  9. final View child = children[i];
  10. child.dispatchAttachedToWindow(info,
  11. combineVisibility(visibility, child.getVisibility()));
  12. }
  13. final int transientCount = mTransientIndices == null ? 0 : mTransientIndices.size();
  14. for (int i = 0; i < transientCount; ++i) {
  15. View view = mTransientViews.get(i);
  16. view.dispatchAttachedToWindow(info,
  17. combineVisibility(visibility, view.getVisibility()));
  18. }
  19. }
  20. // View
  21. void dispatchAttachedToWindow(AttachInfo info, int visibility) {
  22. mAttachInfo = info;
  23. // ...
  24. }

看到这里,大家可能忘记我们开始刚刚要做什么了。

我们是在看 View.post 的流程,再回顾一下 View.post 的代码:

  1. // View.java
  2. public boolean post(Runnable action) {
  3. final AttachInfo attachInfo = mAttachInfo;
  4. if (attachInfo != null) {
  5. return attachInfo.mHandler.post(action);
  6. }
  7. getRunQueue().post(action);
  8. return true;
  9. }

现在我们知道 attachInfo 是什么了,是 ViewRootImpl 首次触发 performTraversals 传进来的,也就是触发 performTraversals 之后,View.post 都是通过 ViewRootImpl 内部的 Handler 进行处理的。

如果在 performTraversals 之前或者 mAttachInfo 置为空以后进行执行,则通过 RunQueue 进行处理。

那我们再看看 getRunQueue().post(action); 做了些什么事情。

这里的 RunQueue 其实是 HandlerActionQueue。

HandlerActionQueue 的代码看一下。

  1. public class HandlerActionQueue {
  2. public void post(Runnable action) {
  3. postDelayed(action, 0);
  4. }
  5. public void postDelayed(Runnable action, long delayMillis) {
  6. final HandlerAction handlerAction = new HandlerAction(action, delayMillis);
  7. synchronized (this) {
  8. if (mActions == null) {
  9. mActions = new HandlerAction[4];
  10. }
  11. mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
  12. mCount++;
  13. }
  14. }
  15. public void executeActions(Handler handler) {
  16. synchronized (this) {
  17. final HandlerAction[] actions = mActions;
  18. for (int i = 0, count = mCount; i < count; i++) {
  19. final HandlerAction handlerAction = actions[i];
  20. handler.postDelayed(handlerAction.action, handlerAction.delay);
  21. }
  22. mActions = null;
  23. mCount = 0;
  24. }
  25. }
  26. }

通过上面的代码我们可以看到,执行 getRunQueue().post(action); 其实是将代码添加到 mActions 进行保存,然后在 executeActions 的时候进行执行。

executeActions 执行的时机只有一个,就是在 dispatchAttachedToWindow(AttachInfo info, int visibility) 里面调用的。

  1. void dispatchAttachedToWindow(AttachInfo info, int visibility) {
  2. mAttachInfo = info;
  3. if (mRunQueue != null) {
  4. mRunQueue.executeActions(info.mHandler);
  5. mRunQueue = null;
  6. }
  7. }

看到这里我们就知道了,View.post 和 Handler.post 的区别就是:

这里我们又可以回答一个问题了,就是为什么 View.post 里可以拿到 View 的宽高信息呢?

因为 View.post 的 Runnable 执行的时候,已经执行过 performTraversals 了,也就是 View 的 measure layout draw 方法都执行过了,自然可以获取到 View 的宽高信息了。

20、为什么 Android6.0 及以后的版本用 eventfd 替代 pipe 作为通信方案?

https://github.com/huanzhiyazi/articles/blob/master/%E6%8A%80%E6%9C%AF/android/Looper%E4%BA%8B%E4%BB%B6%E9%80%9A%E7%9F%A5%E5%8E%9F%E7%90%86/Looper%E4%BA%8B%E4%BB%B6%E9%80%9A%E7%9F%A5%E5%8E%9F%E7%90%86.md

21、callback runnable message调用顺序

  1. public void dispatchMessage(Message msg) {
  2. if (msg.callback != null) {
  3. handleCallback(msg);
  4. } else {
  5. if (mCallback != null) {
  6. if (mCallback.handleMessage(msg)) {
  7. return;
  8. }
  9. }
  10. handleMessage(msg);
  11. }
  12. }

22、postDelay如何实现精确延迟

Handler.postDelayed()精确延迟指定时间的原理

nativePollOnce

nativeWake()
唤醒

enqueueMessage(msg)

  1. boolean enqueueMessage(Message msg, long when) {
  2. if (msg.target == null) {
  3. throw new IllegalArgumentException("Message must have a target.");
  4. }
  5. if (msg.isInUse()) {
  6. throw new IllegalStateException(msg + " This message is already in use.");
  7. }
  8. synchronized (this) {
  9. if (mQuitting) {
  10. IllegalStateException e = new IllegalStateException(
  11. msg.target + " sending message to a Handler on a dead thread");
  12. Log.w(TAG, e.getMessage(), e);
  13. msg.recycle();
  14. return false;
  15. }
  16. msg.markInUse();
  17. msg.when = when;
  18. Message p = mMessages;
  19. boolean needWake;
  20. if (p == null || when == 0 || when < p.when) {
  21. // New head, wake up the event queue if blocked.
  22. msg.next = p;
  23. mMessages = msg;
  24. needWake = mBlocked;
  25. } else {
  26. // Inserted within the middle of the queue. Usually we don't have to wake
  27. // up the event queue unless there is a barrier at the head of the queue
  28. // and the message is the earliest asynchronous message in the queue.
  29. needWake = mBlocked && p.target == null && msg.isAsynchronous();
  30. Message prev;
  31. for (;;) {
  32. prev = p;
  33. p = p.next;
  34. if (p == null || when < p.when) {
  35. break;
  36. }
  37. if (needWake && p.isAsynchronous()) {
  38. needWake = false;
  39. }
  40. }
  41. msg.next = p; // invariant: p == prev.next
  42. prev.next = msg;
  43. }
  44. // We can assume mPtr != 0 because mQuitting is false.
  45. if (needWake) {
  46. nativeWake(mPtr);
  47. }
  48. }
  49. return true;
  50. }

next()

23、Handler为什么会内存泄漏?泄漏的时候,GC Root是谁?

Handler 引起的内存泄露分析以及解决方法
面试官:Handler内存泄露的原因是什么?我:就这?太简单了吧,但我却被挂了...
【证】:那些可作为GC Roots的对象

  1. Looper ——> messagequeue ——> message ——> Handler ——> Activity
  1. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  2. private static Looper sMainLooper;
  3. public static void loop() {
  4. final Looper me = myLooper();
  5. final MessageQueue queue = me.mQueue;
  6. for (;;) {
  7. ...
  8. }
  9. }

在java中,可作为GC Roots的对象有:
1.虚拟机栈(栈帧中的本地变量表)中引用的对象;
2.方法区中的类静态属性引用的对象;
3.方法区中常量引用的对象;
4.本地方法栈中JNI(即一般说的Native方法)中引用的对象

我们来看:

所以对应的GC Root有多个,都是有可能的

24、当MessageQueue空闲的时候,会调用nativePollOnce阻塞主线程,调用nativeWake会唤醒主线程,而主线程已经被阻塞了,谁来唤醒呢?

腾讯面试挂了 | 面试官:说说Android中Looper在主线程中死循环为什么没有导致界面的卡死?

因为主线程已经阻塞,不可能在发送message,所以想要唤醒,就只能通过其他线程了:

25、为什么选择 epoll,而不用 select/poll?

在 IO多路复用——selct,poll,epoll 中我们总结 epoll 相对于 select/poll 的主要性能优势有两点:

参考

一文读懂Handler机制全家桶
面试官带你学安卓-Handler这些知识点你都知道吗
一文读懂ViewPost的原理及缺陷
Looper事件通知原理.md
最通俗易懂的 Handler 源码解析
https://blog.csdn.net/chuyouyinghe/article/details/124141824

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注