Handler消息机制 -- 源码解析

Handler消息机制相关类介绍

  • Message:是在线程之间传递的消息,它可以在内部携带少量的消息,用于在不同线程之间交换数据。
  • Handler:处理者的意思,它主要是用于发送和处理消息。发送消息一般使用Handler的sendMessage()方法,接收消息使用Handler的handleMessage()方法。
  • MessageQueue:消息队列的意思,它主要用于存放所有通过Handler发送的消息,每个线程中只会有一个MessageQueue对象。
  • Looper:是每个线程的MessageQueue管家,调用Looper的Loop方法,就会进入到一个无限循环当中,然后每当发现MessageQueue中存在一条消息,就会将它取出并传递到Handler的handleMessage()方法中,每一个线程也只会有一个Looper对象。
  • ThreadLocal:是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。线程本地变量,存放Looper对象。每个线程对应自己的Looper。

Message的生成

  • new Message()
  • Message.obtain()
  • Handler.obtain()

Handler 类

  1. Handler handler = new Handler() { // 匿名子类对象(),调用父类默认的构造函数
  2. public void handleMessage(Message msg) {
  3. // 更新UI操作
  4. }
  5. }
  6. // Handler类的默认构造函数
  7. public Handler() {
  8. this(null, false);
  9. }
  10. public Handler(Callback callback, boolean async) {
  11. if (FIND_POTENTIAL_LEAKS) {
  12. final Class<? extends Handler> klass = getClass();
  13. if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
  14. (klass.getModifiers() & Modifier.STATIC) == 0) {
  15. Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
  16. klass.getCanonicalName());
  17. }
  18. }
  19. // Looper 的静态方法myLooper(),获取到本线程的Looper对象,如果是在主线程中,则设置Looper对象是在ActivityThread类的main()方法中设置。
  20. mLooper = Looper.myLooper();
  21. if (mLooper == null) {
  22. throw new RuntimeException(
  23. "Can't create handler inside thread that has not called Looper.prepare()");
  24. }
  25. // 获取MessageQueue对象
  26. mQueue = mLooper.mQueue;
  27. mCallback = callback;
  28. mAsynchronous = async;
  29. }

ActivityThread 类中的main方法如下:

  1. public static final void main(String[] args) {
  2. ...
  3. //Looper对象的初始化,放到线程本地变量中
  4. Looper.prepareMainLooper();
  5. if (sMainThreadHandler == null) {
  6. sMainThreadHandler = new Handler();
  7. }
  8. ....
  9. //轮询器轮询取消息
  10. Looper.loop();
  11. ....
  12. }
  13. }

Looper 类

  1. // 创建线程本地变量,存放Looper对象
  2. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  3. // 初始化主线程的Looper对象
  4. public static void prepareMainLooper() {
  5. prepare(false);
  6. synchronized (Looper.class) {
  7. if (sMainLooper != null) {
  8. // 只能初始化一次,否则会报异常
  9. throw new IllegalStateException("The main Looper has already been prepared.");
  10. }
  11. sMainLooper = myLooper();
  12. }
  13. }
  14. // 参数quitAllowed false:不允许中断;true:允许中断
  15. private static void prepare(boolean quitAllowed) {
  16. if (sThreadLocal.get() != null) {
  17. throw new RuntimeException("Only one Looper may be created per thread");
  18. }
  19. // 把Looper对象保存到ThreadLocal中
  20. sThreadLocal.set(new Looper(quitAllowed));
  21. }
  22. // Looper的构造方法
  23. private Looper(boolean quitAllowed) {
  24. // 创建MessageQueue对象,并设置是否可以中断
  25. mQueue = new MessageQueue(quitAllowed);
  26. mThread = Thread.currentThread();
  27. }
  28. // 调用此方法创建Looper,是可以中断的
  29. public static void prepare() {
  30. prepare(true);
  31. }

Handler 发送消息

  1. // 1、handler对象 sendMessage()
  2. public final boolean sendMessage(Message msg) {
  3. return sendMessageDelayed(msg, 0);
  4. }
  5. // 2、
  6. public final boolean sendMessageDelayed(Message msg, long delayMillis) {
  7. if (delayMillis < 0) {
  8. delayMillis = 0;
  9. }
  10. // SystemClock.uptimeMillis() 获取系统的时间,从开机时间算起
  11. return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
  12. }
  13. // 3、
  14. public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
  15. // 获取MessageQueue对象
  16. MessageQueue queue = mQueue;
  17. if (queue == null) {
  18. RuntimeException e = new RuntimeException(
  19. this + " sendMessageAtTime() called with no mQueue");
  20. Log.w("Looper", e.getMessage(), e);
  21. return false;
  22. }
  23. return enqueueMessage(queue, msg, uptimeMillis);
  24. }
  25. // 4、
  26. private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
  27. // this 就是当前Handler对象,把Handler对象给msg对象的target属性
  28. msg.target = this;
  29. if (mAsynchronous) {
  30. msg.setAsynchronous(true);
  31. }
  32. // 消息队列按照消息的进入顺序和发送时间排序,唤醒looper轮询器
  33. return queue.enqueueMessage(msg, uptimeMillis);
  34. }

MessageQueue 插入消息

  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. // 如果消息为空,或者获取当前消息的时间为0,或者当前消息的时间比消息队列的第一个消息的时间小,则把当前消息插入到消息队列的头部
  21. if (p == null || when == 0 || when < p.when) {
  22. // New head, wake up the event queue if blocked.
  23. msg.next = p;
  24. mMessages = msg;
  25. needWake = mBlocked;
  26. } else {
  27. // Inserted within the middle of the queue. Usually we don't have to wake
  28. // up the event queue unless there is a barrier at the head of the queue
  29. // and the message is the earliest asynchronous message in the queue.
  30. needWake = mBlocked && p.target == null && msg.isAsynchronous();
  31. // 保存当前消息队列
  32. Message prev;
  33. for (;;) {
  34. prev = p;
  35. // 获取下一个消息
  36. p = p.next;
  37. if (p == null || when < p.when) {
  38. break;
  39. }
  40. if (needWake && p.isAsynchronous()) {
  41. needWake = false;
  42. }
  43. }
  44. // 插入消息,Message是一个单链表形式,要找到插入消息的前一个位置和后一个位置
  45. msg.next = p; // invariant: p == prev.next
  46. prev.next = msg;
  47. }
  48. // We can assume mPtr != 0 because mQuitting is false.
  49. if (needWake) {
  50. nativeWake(mPtr);
  51. }
  52. }
  53. return true;
  54. }

Looper 轮询器取消息

  1. public static void loop() {
  2. // 获取当前的Looper对象
  3. final Looper me = myLooper();
  4. if (me == null) {
  5. throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
  6. }
  7. // 获取MessageQueue对象
  8. final MessageQueue queue = me.mQueue;
  9. // Make sure the identity of this thread is that of the local process,
  10. // and keep track of what that identity token actually is.
  11. Binder.clearCallingIdentity();
  12. final long ident = Binder.clearCallingIdentity();
  13. for (;;) {
  14. // 没有消息就阻塞,有消息就唤醒
  15. Message msg = queue.next(); // might block
  16. if (msg == null) {
  17. // No message indicates that the message queue is quitting.
  18. return;
  19. }
  20. // This must be in a local variable, in case a UI event sets the logger
  21. Printer logging = me.mLogging;
  22. if (logging != null) {
  23. logging.println(">>>>> Dispatching to " + msg.target + " " +
  24. msg.callback + ": " + msg.what);
  25. }
  26. // 1、msg.target对象就是前面设置的handler对象
  27. msg.target.dispatchMessage(msg);
  28. if (logging != null) {
  29. logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
  30. }
  31. // Make sure that during the course of dispatching the
  32. // identity of the thread wasn't corrupted.
  33. final long newIdent = Binder.clearCallingIdentity();
  34. if (ident != newIdent) {
  35. Log.wtf(TAG, "Thread identity changed from 0x"
  36. + Long.toHexString(ident) + " to 0x"
  37. + Long.toHexString(newIdent) + " while dispatching to "
  38. + msg.target.getClass().getName() + " "
  39. + msg.callback + " what=" + msg.what);
  40. }
  41. // 2、消息回收利用
  42. msg.recycleUnchecked();
  43. }
  44. }

MessageQueue next()方法取消息

  1. Message next() {
  2. // Return here if the message loop has already quit and been disposed.
  3. // This can happen if the application tries to restart a looper after quit
  4. // which is not supported.
  5. final long ptr = mPtr;
  6. if (ptr == 0) {
  7. return null;
  8. }
  9. int pendingIdleHandlerCount = -1; // -1 only during first iteration
  10. int nextPollTimeoutMillis = 0;
  11. for (;;) {
  12. if (nextPollTimeoutMillis != 0) {
  13. Binder.flushPendingCommands();
  14. }
  15. nativePollOnce(ptr, nextPollTimeoutMillis);
  16. synchronized (this) {
  17. // Try to retrieve the next message. Return if found.
  18. final long now = SystemClock.uptimeMillis();
  19. Message prevMsg = null;
  20. Message msg = mMessages;
  21. if (msg != null && msg.target == null) {
  22. // Stalled by a barrier. Find the next asynchronous message in the queue.
  23. do {
  24. prevMsg = msg;
  25. msg = msg.next;
  26. } while (msg != null && !msg.isAsynchronous());
  27. }
  28. if (msg != null) {
  29. if (now < msg.when) {
  30. // Next message is not ready. Set a timeout to wake up when it is ready.
  31. // 如果当前时间,小于msg的时间,则等待并计算等待时间
  32. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
  33. } else {
  34. // Got a message.
  35. mBlocked = false;
  36. if (prevMsg != null) {
  37. prevMsg.next = msg.next;
  38. } else {
  39. // 从消息队列中取出消息头
  40. mMessages = msg.next;
  41. }
  42. // 把取出的消息的next设置为null,取消与下一个节点的关联
  43. msg.next = null;
  44. if (DEBUG) Log.v(TAG, "Returning message: " + msg);
  45. msg.markInUse();
  46. return msg;
  47. }
  48. } else {
  49. // No more messages.
  50. nextPollTimeoutMillis = -1;
  51. }
  52. // Process the quit message now that all pending messages have been handled.
  53. if (mQuitting) {
  54. dispose();
  55. return null;
  56. }
  57. // If first time idle, then get the number of idlers to run.
  58. // Idle handles only run if the queue is empty or if the first message
  59. // in the queue (possibly a barrier) is due to be handled in the future.
  60. if (pendingIdleHandlerCount < 0
  61. && (mMessages == null || now < mMessages.when)) {
  62. pendingIdleHandlerCount = mIdleHandlers.size();
  63. }
  64. if (pendingIdleHandlerCount <= 0) {
  65. // No idle handlers to run. Loop and wait some more.
  66. mBlocked = true;
  67. continue;
  68. }
  69. if (mPendingIdleHandlers == null) {
  70. mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
  71. }
  72. mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
  73. }
  74. // Run the idle handlers.
  75. // We only ever reach this code block during the first iteration.
  76. for (int i = 0; i < pendingIdleHandlerCount; i++) {
  77. final IdleHandler idler = mPendingIdleHandlers[i];
  78. mPendingIdleHandlers[i] = null; // release the reference to the handler
  79. boolean keep = false;
  80. try {
  81. keep = idler.queueIdle();
  82. } catch (Throwable t) {
  83. Log.wtf(TAG, "IdleHandler threw exception", t);
  84. }
  85. if (!keep) {
  86. synchronized (this) {
  87. mIdleHandlers.remove(idler);
  88. }
  89. }
  90. }
  91. // Reset the idle handler count to 0 so we do not run them again.
  92. pendingIdleHandlerCount = 0;
  93. // While calling an idle handler, a new message could have been delivered
  94. // so go back and look again for a pending message without waiting.
  95. nextPollTimeoutMillis = 0;
  96. }
  97. }

Handler dispatchMessage()处理消息

  1. public void dispatchMessage(Message msg) {
  2. if (msg.callback != null) {
  3. // 如果设置了消息的callback,则处理callback
  4. handleCallback(msg);
  5. } else {
  6. if (mCallback != null) {
  7. if (mCallback.handleMessage(msg)) {
  8. return;
  9. }
  10. }
  11. // 走handleMessage方法处理消息
  12. handleMessage(msg);
  13. }
  14. }
  15. // 回调callback的run方法
  16. private static void handleCallback(Message message) {
  17. message.callback.run();
  18. }
  19. // handler的handleMessage空方法,让子类去实现,处理业务逻辑
  20. public void handleMessage(Message msg) {
  21. }

Message 消息回收

  1. // 消息回收方法
  2. void recycleUnchecked() {
  3. // Mark the message as in use while it remains in the recycled object pool.
  4. // Clear out all other details.
  5. // 消除message消息对象里的属性值
  6. flags = FLAG_IN_USE;
  7. what = 0;
  8. arg1 = 0;
  9. arg2 = 0;
  10. obj = null;
  11. replyTo = null;
  12. sendingUid = -1;
  13. when = 0;
  14. target = null;
  15. callback = null;
  16. data = null;
  17. synchronized (sPoolSync) { // 就是Object对象满足synchronized语法
  18. if (sPoolSize < MAX_POOL_SIZE) { // MAX_POOL_SIZE=50
  19. next = sPool; // 设置新的回收消息的下一个为sPool
  20. sPool = this; // 设置该消息为新的消息头
  21. sPoolSize++; // 回收的消息+1
  22. }
  23. }
  24. }

Handler消息机制流程图


在子线程中使用Handler机制

  1. * class LooperThread extends Thread {
  2. * public Handler mHandler;
  3. *
  4. * public void run() {
  5. * Looper.prepare(); // 创建Looper对象
  6. *
  7. * mHandler = new Handler() {
  8. * public void handleMessage(Message msg) {
  9. * // process incoming messages here
  10. * }
  11. * };
  12. *
  13. * Looper.loop(); // 开启Looper轮询器,读取消息,没有消息则等待
  14. * }
  15. * }













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章