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. * }













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