我们通过handler发送消息一般会通过调用Handler类的sendMessage方法,下面就从sendMessage开始分析消息发送的过程。基本的流程如图所示。
源码分析 sendMessage为例分析
frameworks/base/core/java/android/os/Handler.java
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
成员函数sendMessage会调用到sendMessageAtTime其中参数uptimeMillis为系统当前时间加上uptimeMillis延时时间得到的一个将来时间。sendMessageAtTime会调用
enqueueMessage方法将消息放入到MessageQueue的队列中。MessageQueue对象的引用queue初始化是Handler构造方法中
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
frameworks/base/core/java/android/os/MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
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;
}
一个消息队列中的消息的处理是按照时间从小到大的顺序来排列的。因此将一个消息发送到消息队列中,首先会根据消息的时间找到其在消息队列中合适的位置,然后将其插入到消息队列中。
根据源码我们可以将消息插入到消息队列中分为四种情况。
- p == null 目标消息队列为空队列
- when == 0 插入的消息处理时间等于0
- when < p.when 插入消息的处理时间小于保存在目标消息队列头的时间
- when >= p.when 插入消息的处理时间大于等于保存在目标消息队列头的时间
对于1、2、3这三种情况由于目标消息队列的头部消息发生了变化,因此我们就需要将目标线程唤醒,以便确保对保存在目标消息队列头部的新消息进行处理。但是如果目标线程不是处于睡眠等待状态就不需要执行唤醒的动作。MessageQueue中的成员变量mBlocked记录了目标线程的状态, 如果mBlocked的值为true就表示目标线程正在处于睡眠等待状态,需要将它唤醒。
对于4这种情况由于目标消息队列头部的消息没有发生变化,因此不需要对目标线程执行唤醒操作needWake的值为false。
如果needWake的值为true就会调用nativeWake方法
frameworks/base/core/jni/android_os_MessageQueue.cpp
static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->wake();
}
void NativeMessageQueue::wake() {
mLooper->wake();
}
参数ptr指向的是MessageQueue对象的成员变量mPtr,mPtr是NativeMessageQueue对象的地址,在android_os_MessageQueue_nativeWake方法中将其转换为了一个NativeMessageQueue对象,接着会调用wake其wake方法,接着会调用C++层Looper对象的wake方法。
void Looper::wake() {
uint64_t inc = 1;
ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
if (nWrite != sizeof(uint64_t)) {
if (errno != EAGAIN) {
LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
mWakeEventFd.get(), nWrite, strerror(errno));
}
}
}
调用write向管道中写入&inc,这时候目标线程就会由于管道发生了IO写操作而被唤醒。
消息的发送过程就分析完了。