Android基礎(chǔ)之消息處理機(jī)制


簡介

消息驅(qū)動(dòng)是一種進(jìn)程/線程的運(yùn)行模式,內(nèi)部或者外部的消息事件被放到進(jìn)程/線程的消息隊(duì)列中按序處理是現(xiàn)在的操作系統(tǒng)普遍采用的機(jī)制.Android也是采用了消息驅(qū)動(dòng)的機(jī)制來處理各種外部按鍵,觸屏,系統(tǒng)Intent,廣播事件等消息.

Android的消息隊(duì)列是線程相關(guān)的,每啟動(dòng)一個(gè)線程,都可以在內(nèi)部創(chuàng)建一個(gè)消息隊(duì)列,然后在消息隊(duì)列中不斷循環(huán)檢查是否有新的消息需要處理,如果有,則對(duì)該消息進(jìn)行處理,如果沒有,線程就進(jìn)入休眠狀態(tài)直到有新的消息需要處理為止.


數(shù)據(jù)模型

Android中與消息機(jī)制相關(guān)的類主要有Looper,MessageQueue,Handler,Message,相關(guān)的代碼主要在以下文件中:

  • frameworks/base/core/java/android/os/Looper.java
  • frameworks/base/core/java/android/os/Message.java
  • frameworks/base/core/java/android/os/MessageQueue.java
  • frameworks/base/core/java/android/os/Handler.java
  • frameworks/base/core/jni/android_os_MessageQueue.cpp
  • system/core/libutils/Looper.cpp
  • Looper
    Looper對(duì)象是用來創(chuàng)建消息隊(duì)列并進(jìn)入消息循環(huán)處理的.每個(gè)線程只能有一個(gè)Looper對(duì)象,同時(shí)對(duì)應(yīng)著一個(gè)MessageQueue,發(fā)送到該線程的消息都將存放在該隊(duì)列中,并由Looper循環(huán)處理。Android默認(rèn)只為主線程)(UI線程)創(chuàng)建了Looper,所以當(dāng)我們新建線程需要使用消息隊(duì)列時(shí)必須手動(dòng)創(chuàng)建Looper.
  • MessageQueue
    MessageQueue即消息隊(duì)列,由Looper創(chuàng)建管理,一個(gè)Looper對(duì)象對(duì)應(yīng)一個(gè)MessageQueue對(duì)象.
  • Handler
    Handler是消息的接收與處理者,Handler將Message添加到消息隊(duì)列,同時(shí)也通過Handler的回調(diào)方法handleMessage()處理對(duì)應(yīng)的消息.一個(gè)Handler對(duì)象只能關(guān)聯(lián)一個(gè)Looper對(duì)象,但多個(gè)Handler對(duì)象可以關(guān)聯(lián)到同一個(gè)Looper.默認(rèn)情況下Handler會(huì)關(guān)聯(lián)到實(shí)例化Handler線程的Lopper,也可以通過Handler的構(gòu)造函數(shù)的Looper參數(shù)指定Handler關(guān)聯(lián)到某個(gè)線程的Looper,即發(fā)送消息到某個(gè)指定線程并在該線程中回調(diào)Handler處理該消息.
  • Message
    Message是消息的載體,Parcelable的派生類,通過其成員變量target關(guān)聯(lián)到Handler對(duì)象.

它們之間關(guān)系如下圖示:

Handler,Looper,MessageQueue之間的關(guān)系
Handler,Looper,MessageQueue之間的關(guān)系

在代碼中我們一般如下使用線程的消息機(jī)制:

class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
}

線程消息隊(duì)列的創(chuàng)建

線程的消息隊(duì)列通過Looper創(chuàng)建并維護(hù)的,主線程中調(diào)用Looper.prepareMainLooper(),其他子線程中調(diào)用Looper.prepare()來創(chuàng)建消息隊(duì)列.一個(gè)線程多次調(diào)用prepareMainLooper()或prepare()將會(huì)拋出異常.

在介紹消息隊(duì)列創(chuàng)建之前,首先了解一下Looper與MessageQueue,再看消息隊(duì)列創(chuàng)建的流程.

  1. Looper類的主要成員變量與方法如下:
public final class Looper {
      static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
      private static Looper sMainLooper;  
      final MessageQueue mQueue;
      final Thread mThread;

      public static void prepare() {...}
      private static void prepare(boolean quitAllowed) {...}
      public static void prepareMainLooper() {...}
      public static Looper getMainLooper() {...}
      public static void loop() {...}
}
  • sThreadLocal是靜態(tài)成員變量,用于保存線程私有的Looper對(duì)象
  • sMainLooper是主線程的Looper對(duì)象.在prepareMainLooper()中賦值,可通過調(diào)用getMainLooper獲取
  • mQueue即消息隊(duì)列,在Looper構(gòu)造函數(shù)中初始化
  • mThread即Looper所在的線程
  1. MessageQueue類的主要成員變量與方法如下:
public final class MessageQueue {
      private final boolean mQuitAllowed;
      private long mPtr;
      Message mMessages;

      MessageQueue(boolean quitAllowed) {...}
      boolean enqueueMessage(Message msg, long when) {...}
      Message next() {...}
}
  • mQuitAllowed代表是否允許退出消息循環(huán),主線程中默認(rèn)為false,子線程默認(rèn)false
  • mPtr保存的是NativeMessageQueue的地址,通過該地址就可以找到j(luò)ava層MessageQueue所對(duì)應(yīng)native的MessageQueue.
  • mMessages即消息隊(duì)列,通過mMessages可以遍歷整個(gè)消息隊(duì)列
  1. 消息隊(duì)列的創(chuàng)建:
    消息隊(duì)列的創(chuàng)建從Looper.prepare()/Looper.prepareMainLooper()開始
public static void prepare() {
      prepare(true);
}
public static void prepareMainLooper() {
      prepare(false);
      synchronized (Looper.class) {
          if (sMainLooper != null) {
              throw new IllegalStateException("The main Looper has already been prepared.");
          }
          sMainLooper = myLooper();
      }
}
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));
}
private Looper(boolean quitAllowed) {
      mQueue = new MessageQueue(quitAllowed);
      mThread = Thread.currentThread();
}

通過調(diào)用prepare()或prepareMainLooper()創(chuàng)建Looper對(duì)象,然后保存到sThreadLocal中,sThreadLocal是模板類ThreadLocal<T>,它通過線程ID與對(duì)象關(guān)聯(lián)的方式實(shí)現(xiàn)線程本地存儲(chǔ)功能.這樣放入sThreadLocal對(duì)象中的Looper對(duì)象就與創(chuàng)建它的線程關(guān)聯(lián)起來了.所以可以從sThreadLocal中獲取到保存的Looper對(duì)象:

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

主線程的Loopper對(duì)象保存在sMainLooper,可以通過getMainLooper獲取

public static Looper getMainLooper() {
      synchronized (Looper.class) {
          return sMainLooper;
      }
}

創(chuàng)建Looper同時(shí)會(huì)創(chuàng)建Looper關(guān)聯(lián)的MessageQueue并賦值給成員變量mQueue,接下來再看new MessageQueue(quitAllowed)的過程:

MessageQueue(boolean quitAllowed) {
      mQuitAllowed = quitAllowed;
      mPtr = nativeInit();
}

可以看到,直接調(diào)用了nativeInit().這個(gè)JNI方法定義在android_os_MessageQueue.cpp

static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
      NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
      if (!nativeMessageQueue) {
          jniThrowRuntimeException(env, "Unable to allocate native queue");
          return 0;
      }

      nativeMessageQueue->incStrong(env);
      return reinterpret_cast<jlong>(nativeMessageQueue);
}

nativeInit()中首先創(chuàng)建了nativeMessageQueue,然后又將nativeMessageQueue的地址賦值給java層的mPtr,所以java層的MessageQueue就可以通過mPtr找到nativeMessageQueue了.
再看new NativeMessageQueue()過程,NativeMessageQueue的構(gòu)造如下:

NativeMessageQueue::NativeMessageQueue() : mInCallback(false), mExceptionObj(NULL) {
      mLooper = Looper::getForThread();
      if (mLooper == NULL) {
          mLooper = new Looper(false);
          Looper::setForThread(mLooper);
      }
}

它首先通過Looper::getForThread()判斷當(dāng)前線程是否已創(chuàng)建過Looper對(duì)象,如果沒有則創(chuàng)建.注意,這個(gè)Looper對(duì)象是實(shí)現(xiàn)在JNI層的,與上面Java層的Looper是不一樣的,不過也是對(duì)應(yīng)的關(guān)系.JNI層的Looper對(duì)象的創(chuàng)建過程是在Looper.cpp中實(shí)現(xiàn)的.

Looper::Looper(bool allowNonCallbacks) :
        mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
        mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
        mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
    mWakeEventFd = eventfd(0, EFD_NONBLOCK);
    LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd.  errno=%d", errno);

    AutoMutex _l(mLock);
    rebuildEpollLocked();
}

創(chuàng)建eventfd并賦值給mWakeEventFd,在以前的Android版本上,這里創(chuàng)建的是pipe管道.eventfd是較新的API,被用作一個(gè)事件等待/響應(yīng),實(shí)現(xiàn)了線程之間事件通知.

void Looper::rebuildEpollLocked() {
    // Close old epoll instance if we have one.
    if (mEpollFd >= 0) {
#if DEBUG_CALLBACKS
        ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
#endif
        close(mEpollFd);
    }

    // Allocate the new epoll instance and register the wake pipe.
    mEpollFd = epoll_create(EPOLL_SIZE_HINT);
    LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance.  errno=%d", errno);

    struct epoll_event eventItem;
    memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
    eventItem.events = EPOLLIN;
    eventItem.data.fd = mWakeEventFd;
    int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);
    LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance.  errno=%d",
            errno);

    for (size_t i = 0; i < mRequests.size(); i++) {
        const Request& request = mRequests.valueAt(i);
        struct epoll_event eventItem;
        request.initEventItem(&eventItem);

        int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, request.fd, & eventItem);
        if (epollResult < 0) {
            ALOGE("Error adding epoll events for fd %d while rebuilding epoll set, errno=%d",
                    request.fd, errno);
        }
    }
}

rebuildEpollLocked中通過epoll_create創(chuàng)建了一個(gè)epoll專用的文件描述符,EPOLL_SIZE_HINT表示mEpollFd上能監(jiān)控的最大文件描述符數(shù).最后調(diào)用epoll_ctl監(jiān)控mWakeEventFd文件描述符的EPOLLIN事件,即當(dāng)eventfd中有內(nèi)容可讀時(shí),就喚醒當(dāng)前正在等待的線程.

C++層的這個(gè)Looper對(duì)象創(chuàng)建好了之后,就返回到JNI層的NativeMessageQueue的構(gòu)造函數(shù),再返回到Java層的消息隊(duì)列MessageQueue的創(chuàng)建過程,最后從Looper的構(gòu)造函數(shù)中返回.線程消息隊(duì)列的創(chuàng)建過程也就此完成.

總結(jié)一下:

  • 首先在Java層創(chuàng)建了一個(gè)Looper對(duì)象,然后創(chuàng)建MessageQueue對(duì)象mQueue,進(jìn)入MessageQueue的創(chuàng)建過程
  • MessageQueue在JNI層創(chuàng)建了一個(gè)NativeMessageQueue對(duì)象,并將這個(gè)對(duì)象保存在MessageQueue的成員變量mPtr中
  • 在JNI層,創(chuàng)建了NativeMessageQueue對(duì)象時(shí),會(huì)創(chuàng)建了一個(gè)Looper對(duì)象,保存在JNI層的NativeMessageQueue對(duì)象的成員變量mLooper中,這個(gè)對(duì)象的作用是,當(dāng)Java層的消息隊(duì)列中沒有消息時(shí),就使Android應(yīng)用程序線程進(jìn)入等待狀態(tài),而當(dāng)Java層的消息隊(duì)列中來了新的消息后,就喚醒Android應(yīng)用程序的線程來處理這個(gè)消息
  • 關(guān)于java層與JNI層的Looper,MessageQueue對(duì)象可以這樣理解,java層的Looper,MessageQueue主要實(shí)現(xiàn)了消息隊(duì)列發(fā)送處理邏輯,而JNI層的主要實(shí)現(xiàn)是線程的等待/喚醒.在邏輯上他們還是一一對(duì)應(yīng)的關(guān)系,只不過側(cè)重點(diǎn)不同.


    java與jni層Looper,MessageQueue關(guān)系
    java與jni層Looper,MessageQueue關(guān)系

線程消息隊(duì)列的循環(huán)

當(dāng)線程消息隊(duì)列創(chuàng)建完成后,即進(jìn)入消息隊(duì)列循環(huán)處理過程中,Android消息隊(duì)列的循環(huán)通過Loop.Loop()來實(shí)現(xiàn),整個(gè)流程如下圖示.


消息隊(duì)列循環(huán)流程
消息隊(duì)列循環(huán)流程

下面具體來看具體分析

public static void loop() {
      final Looper me = myLooper();
      if (me == null) {
          throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
      }
      final MessageQueue queue = me.mQueue;

      ...
      for (;;) {
          Message msg = queue.next(); // might block
          if (msg == null) {
              // No message indicates that the message queue is quitting.
              return;
          }

          ...
          msg.target.dispatchMessage(msg);
          ...
      }
}

進(jìn)入loop前,首先通過myLooper()拿到前面創(chuàng)建的Looper對(duì)象,如果為null將會(huì)拋出異常,這也就是為什么必須在Looper.loop()之前調(diào)用Looper.prepare()或者Looper.prepareMainLooper()的原因.接下來通過me.mQueue拿到MessageQueue對(duì)象,而后進(jìn)入到無盡循環(huán)處理中.在循環(huán)中通過queue.next()從隊(duì)列中取消息,再調(diào)用msg.target.dispatchMessage(msg)處理.下面看一下queue.next()流程.

Message next() {
      final long ptr = mPtr;
      if (ptr == 0) {
          return null;
      }

      int pendingIdleHandlerCount = -1;
      int nextPollTimeoutMillis = 0;
      for (;;) {
          if (nextPollTimeoutMillis != 0) {
              Binder.flushPendingCommands();
          }

          nativePollOnce(ptr, nextPollTimeoutMillis);

          synchronized (this) {
              final long now = SystemClock.uptimeMillis();
              Message prevMsg = null;
              Message msg = mMessages;
              if (msg != null && msg.target == null) {
                  do {
                      prevMsg = msg;
                      msg = msg.next;
                  } while (msg != null && !msg.isAsynchronous());
              }
              if (msg != null) {
                  if (now < msg.when) {
                      nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                  } else {
                      mBlocked = false;
                      if (prevMsg != null) {
                          prevMsg.next = msg.next;
                      } else {
                          mMessages = msg.next;
                      }
                      msg.next = null;
                      if (false) Log.v("MessageQueue", "Returning message: " + msg);
                      return msg;
                  }
              } else {
                  nextPollTimeoutMillis = -1;
              }

              if (mQuitting) {
                  dispose();
                  return null;
              }

              if (pendingIdleHandlerCount < 0
                      && (mMessages == null || now < mMessages.when)) {
                  pendingIdleHandlerCount = mIdleHandlers.size();
              }
              if (pendingIdleHandlerCount <= 0) {
                  mBlocked = true;
                  continue;
              }

              if (mPendingIdleHandlers == null) {
                  mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
              }
              mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
          }

          for (int i = 0; i < pendingIdleHandlerCount; i++) {
              final IdleHandler idler = mPendingIdleHandlers[i];
              mPendingIdleHandlers[i] = null;

              boolean keep = false;
              try {
                  keep = idler.queueIdle();
              } catch (Throwable t) {
                  Log.wtf("MessageQueue", "IdleHandler threw exception", t);
              }

              if (!keep) {
                  synchronized (this) {
                      mIdleHandlers.remove(idler);
                  }
              }
          }

          pendingIdleHandlerCount = 0;
          nextPollTimeoutMillis = 0;
      }
}

先看一下開始定義的2個(gè)變量的含義,pendingIdleHandlerCount表示消息隊(duì)列空閑消息處理器(IdleHandler)的個(gè)數(shù),nextPollTimeoutMillis表示沒有消息處理時(shí),線程需睡眠等待的時(shí)間.nativePollOnce將會(huì)睡眠等待nextPollTimeoutMillis時(shí)間.從nativePollOnce返回后,再從消息隊(duì)列中取消息,如果沒有任何消息,那么nextPollTimeoutMillis賦值為-1,表示下一次nativePollOnce無限制等待直到其他線程把它喚醒.如果取到消息,比較消息處理的時(shí)間與當(dāng)前時(shí)間,如果消息處理的時(shí)間未到(now < msg.when),那么計(jì)算nextPollTimeoutMillis,等下一次時(shí)間到時(shí)再處理.如果消息處理時(shí)間已到,那么取出消息返回到Looperde的loop中處理.另外如果當(dāng)前沒有消息處理時(shí),會(huì)回調(diào)注冊(cè)的IdleHandler.
下面繼續(xù)分析nativePollOnce.

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
        jlong ptr, jint timeoutMillis) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}
void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
    mPollEnv = env;
    mPollObj = pollObj;
    mLooper->pollOnce(timeoutMillis);
    mPollObj = NULL;
    mPollEnv = NULL;

    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}

最終nativePollOnce調(diào)用的JNI層Looper的pollOnce

int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
    int result = 0;
    for (;;) {
        ...
        if (result != 0) {
            ...
            return result;
        }

        result = pollInner(timeoutMillis);
    }
}

在pollOnce中不斷的循環(huán)調(diào)用pollInner來檢查線程是否有新消息需要處理.如果有新消息處理或者timeoutMillis時(shí)間到,則返回到j(luò)ava層MessageQueue的next()繼續(xù)執(zhí)行.

int Looper::pollInner(int timeoutMillis) {
    ...
    int result = POLL_WAKE;

    struct epoll_event eventItems[EPOLL_MAX_EVENTS];
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
    ...
    for (int i = 0; i < eventCount; i++) {
        int fd = eventItems[i].data.fd;
        uint32_t epollEvents = eventItems[i].events;
        if (fd == mWakeEventFd) {
            if (epollEvents & EPOLLIN) {
                awoken();
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
            }
        } else {
          ...
        }
    }
    ...
    return result;
}

epoll_wait會(huì)監(jiān)聽前面創(chuàng)建的epoll實(shí)例的文件描述符上的IO讀寫事件,如果文件描述上沒有IO事件出現(xiàn),那么則等待timeoutMillis延時(shí),檢測(cè)到EPOLLIN事件即文件描述符上發(fā)生了寫事件,隨后調(diào)用awoken讀出數(shù)據(jù),以便接收新的數(shù)據(jù).

void Looper::awoken() {
    uint64_t counter;
    TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
}

在awoken中讀出數(shù)據(jù).然后一步步返回到j(luò)ava層的MessageQueue繼續(xù)消息處理.


線程消息的發(fā)送

消息的發(fā)送是通過Handler來執(zhí)行的,下面我們從new Handler()開始,一步步分析消息的發(fā)送過程
首先看一下Handler類的主要數(shù)據(jù)成員與方法:

public class Handler {
      final MessageQueue mQueue;
      final Looper mLooper;

      public Handler() {...}
      public Handler(Looper looper, Callback callback) {...}

      private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {...}
      public void handleMessage(Message msg) {...}

      public final boolean sendMessage(Message msg){...}
      public final boolean sendEmptyMessage(int what){...}
      public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {...}
      public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {...}
      public boolean sendMessageAtTime(Message msg, long uptimeMillis) {...}
      ...
      public final boolean post(Runnable r){...}
      public final boolean postAtFrontOfQueue(Runnable r){...}
      public final boolean postAtTime(Runnable r, long uptimeMillis){...}
      public final boolean postDelayed(Runnable r, long delayMillis){...}
}
  • mQueue handler對(duì)應(yīng)的MessageQueue對(duì)象,通過handler發(fā)送的消息都將插入到mQueue隊(duì)列中
  • mLooper handler對(duì)應(yīng)的Looper對(duì)象,如果創(chuàng)建Handler前沒有實(shí)例化Looper對(duì)象將拋出異常.

Handler是與Looper對(duì)象相關(guān)聯(lián)的,我們創(chuàng)建的Handler對(duì)象都會(huì)關(guān)聯(lián)到某一Looper,默認(rèn)情況下,Handler會(huì)關(guān)聯(lián)到創(chuàng)建Handler對(duì)象所在線程的Looper對(duì)象,也可通過Handler的構(gòu)造函數(shù)來指定關(guān)聯(lián)到的Looper.Handler發(fā)送消息有二類接口,post類與send類,一般send類用來發(fā)送傳統(tǒng)帶消息ID的消息,post類用來發(fā)送帶消息處理方法的消息.

下面來看消息發(fā)送的具體流程


消息發(fā)送流程
消息發(fā)送流程

Handler或Post類方法最終都會(huì)調(diào)用enqueueMessage將消息發(fā)送到消息隊(duì)列

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
      msg.target = this;
      if (mAsynchronous) {
          msg.setAsynchronous(true);
      }
      return queue.enqueueMessage(msg, uptimeMillis);
}

Message的成員變量target賦值為this,即關(guān)聯(lián)到handler.然后繼續(xù)調(diào)用MessageQueue的enqueueMessage方法

boolean enqueueMessage(Message msg, long when) {
      if (msg.target == null) {
          throw new IllegalArgumentException("Message must have a target.");
      }
      if (msg.isInUse()) {
          throw new IllegalStateException(msg + " This message is already in use.");
      }

      /// M: Add message protect mechanism @{
      if (msg.hasRecycle) {
          Log.wtf("MessageQueue", "Warning: message has been recycled. msg=" + msg);
          return false;
      }
      /// Add message protect mechanism @}

      synchronized (this) {
          if (mQuitting) {
              IllegalStateException e = new IllegalStateException(
                      msg.target + " sending message to a Handler on a dead thread");
              Log.w("MessageQueue", e.getMessage(), e);
              msg.recycle();
              return false;
          }

          msg.markInUse();
          msg.when = when;
          Message p = mMessages;
          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 {
              // 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;
          }

          // We can assume mPtr != 0 because mQuitting is false.
          if (needWake) {
              nativeWake(mPtr);
          }
      }
      return true;
}

MessageQueue中的enqueueMessage主要工作是將message插入到隊(duì)列,然后根據(jù)情況判斷是否應(yīng)該調(diào)用nativeWake喚醒目標(biāo)線程.當(dāng)前隊(duì)列為空或者插入消息處理時(shí)間延時(shí)為0或者處理時(shí)間小于隊(duì)頭處理時(shí)間時(shí),消息被插入到頭部,否則按時(shí)間遍歷插入到對(duì)應(yīng)位置,并設(shè)置needWake標(biāo)志,needWake是根據(jù)mBlocked來判斷的,mBlocked記錄了當(dāng)前線程是否處于睡眠狀態(tài),如果消息插入隊(duì)頭且線程在睡眠中,neeWake為true,調(diào)用nativeWake喚醒目標(biāo)線程.

static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
      NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
      return nativeMessageQueue->wake();
}
void NativeMessageQueue::wake() {
      mLooper->wake();
}
void Looper::wake() {
    uint64_t inc = 1;
    ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
    if (nWrite != sizeof(uint64_t)) {
        if (errno != EAGAIN) {
            ALOGW("Could not write wake signal, errno=%d", errno);
        }
    }
}

nativeWake最終會(huì)調(diào)用到j(luò)ni層的Looper對(duì)象的wake方法中,Looper wake方法的實(shí)現(xiàn)非常簡單,即向mWakeEventFd寫入一個(gè)uint64_t,這樣目標(biāo)線程就會(huì)因?yàn)閙WakeEventFd發(fā)生的IO事件而喚醒.消息的發(fā)送流程就此結(jié)束.


線程消息的處理

從前面的分析可以知道,當(dāng)線程沒有消息需要處理時(shí),會(huì)在c++層Looper對(duì)象的pollInner中進(jìn)入睡眠等待,當(dāng)有新消息喚醒該目標(biāo)線程時(shí)或這延時(shí)時(shí)間到,執(zhí)行流程將沿著pollInner調(diào)用路徑一直返回,直到j(luò)ava層Looper類的loop.


消息處理流程
消息處理流程

loop中將調(diào)用msg.target.dispatchMessage(msg)處理消息,這里的msg.target就是上面enqueueMessage中所賦值的handler,即進(jìn)入handler的dispatchMessage處理消息

public void dispatchMessage(Message msg) {
      if (msg.callback != null) {
          handleCallback(msg);
      } else {
          if (mCallback != null) {
              if (mCallback.handleMessage(msg)) {
                  return;
              }
          }
          handleMessage(msg);
      }
}

dispatchMessage進(jìn)行消息處理,先檢查是否有設(shè)置msg.callback,如果有則執(zhí)行msg.callback處理消息,如果沒有則繼續(xù)判斷mCallback的執(zhí)行,最后才是handleMessage處理.


訪問我的博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容