版本基于:Android R
0. 前言
在《Android 基于Handler 剖析消息机制》一文中,以 Handler 类为起点详细分析了异步通信,分析了Java 端 Handler 与Looper、MessageQueue、Message 之前的通信关系。
框架如下:
在Java 端的 Looper 中会创建一个 Java 端的 MessageQueue实例,并在loop() 函数中的死循环里通过 queue.next() 不停的获取监听到的下一个 Message,然后将其通过 dispatchMessage() 分发处理。详细看《Android 基于Handler 剖析消息机制》一文第 4.3 节。
在 Java 端的 MessageQueue 实现核心机制是通过 Native 端的 MessageQueue,该类的对象中维护了一个 native Looper,上面说到的 Java 端的next() 函数就是通过 native 端的 epoll 机制 进行阻塞监听。
之前《Android 基于Handler 剖析消息机制》一文只是对 native Looper 做了简单的介绍,本文将重点分析一下 native Looper 实现机制。
1. Looper 类
system/core/libutils/include/utils/Looper.h
class Looper : public RefBase {
protected:
virtual ~Looper();
public:
Looper(bool allowNonCallbacks);
bool getAllowNonCallbacks() const;
int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
inline int pollOnce(int timeoutMillis) {
return pollOnce(timeoutMillis, nullptr, nullptr, nullptr);
}
int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
inline int pollAll(int timeoutMillis) {
return pollAll(timeoutMillis, nullptr, nullptr, nullptr);
}
void wake();
int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
int removeFd(int fd);
void sendMessage(const sp<MessageHandler>& handler, const Message& message);
void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
const Message& message);
void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
const Message& message);
void removeMessages(const sp<MessageHandler>& handler);
void removeMessages(const sp<MessageHandler>& handler, int what);
bool isPolling() const;
static sp<Looper> prepare(int opts);
static void setForThread(const sp<Looper>& looper);
static sp<Looper> getForThread();
private:
...
const bool mAllowNonCallbacks; // immutable
android::base::unique_fd mWakeEventFd; // immutable
Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
...
};
简单了列举了下 Looper 类中的成员,后面根据流程再详细说明。
2. Looper 构造函数
system/core/libutils/Looper.cpp
Looper::Looper(bool allowNonCallbacks)
: mAllowNonCallbacks(allowNonCallbacks),
mSendingMessage(false),
mPolling(false),
mEpollRebuildRequired(false),
mNextRequestSeq(0),
mResponseIndex(0),
mNextMessageUptime(LLONG_MAX) {
mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
AutoMutex _l(mLock);
rebuildEpollLocked();
}
参数 allowNonCallbacks 指定该 Looper 中是否允许在 addFd() 的时候可以不设定 callback,如果为true,则在addFd() 时可以不用设定callback,如果为 false,则在 addFd() 的时候需要指定 callback,否则会报错,详细可以查看 addFd() 函数。
构造函数中主要做了两件事情:
- 创建一个 wakeEventFd;
- 调用 rebuildEpollLocked() 初始化 epoll;
2.1 rebuildEpollLocked()
system/core/libutils/Looper.cpp
void Looper::rebuildEpollLocked() {
//step1,如果是重构epoll 时的逻辑,需要进行reset
if (mEpollFd >= 0) {
#if DEBUG_CALLBACKS
ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
#endif
mEpollFd.reset();
}
//step2,分配一个新的epoll,并将wakeEventFd添加到监听
mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(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.get();
int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &eventItem);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
strerror(errno));
//step3,是否有其他的request,如果有,也重新加入到epoll中监听
//一般request 通过addFd 函数添加
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.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
if (epollResult < 0) {
ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
request.fd, strerror(errno));
}
}
}
大致流程如上面注释,主要是三步:
- 如果是重构 epoll 时的逻辑,需要进行reset;
- 分配一个新的 epoll,并将 wakeEventFd添加到监听;
- 是否有其他的 request,如果有,也重新加入到epoll中监听;
3. MessageHandler 类
system/core/libutils/include/utils/Looper.h
class MessageHandler : public virtual RefBase {
protected:
virtual ~MessageHandler();
public:
/**
* Handles a message.
*/
virtual void handleMessage(const Message& message) = 0;
};
在 Looper.h 中还定义了 MessageHandler 这样的类,同Java 端的 Handler类,都是用来处理消息的。
当创建好 MessageHandler 对象之后,可以通过 Looper::sendMessage() 函数发送消息到Looper 中,Looper 会在后续的 pollOnce() 中进行监听,最终通过 handleMessage() 函数进行回调处理此次消息。
3.1 sendMessage()
在 Looper.h 中我们看到三个详细的函数:
void sendMessage(const sp<MessageHandler>& handler, const Message& message);
void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
const Message& message);
void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
const Message& message);
但其实前面两个函数最终调用的都是 sendMessageAtTime() 函数:
system/core/libutils/Looper.cpp
void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
sendMessageAtTime(now, handler, message);
}
void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
const Message& message) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
sendMessageAtTime(now + uptimeDelay, handler, message);
}
void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
const Message& message) {
#if DEBUG_CALLBACKS
ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
this, uptime, handler.get(), message.what);
#endif
size_t i = 0;
{ // acquire lock
AutoMutex _l(mLock);
size_t messageCount = mMessageEnvelopes.size();
while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
i += 1;
}
MessageEnvelope messageEnvelope(uptime, handler, message);
mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
// Optimization: If the Looper is currently sending a message, then we can skip
// the call to wake() because the next thing the Looper will do after processing
// messages is to decide when the next wakeup time should be. In fact, it does
// not even matter whether this code is running on the Looper thread.
if (mSendingMessage) {
return;
}
} // release lock
// Wake the poll loop only when we enqueue a new message at the head.
if (i == 0) {
wake();
}
}
这里涉及到了 Looper 中的另外一个成员变量:mMessageEnvelopes,这是一个 Vector 类型变量,用以存放通过 sendMessage() 发送到 Looper 中的消息。
如代码所示,会将 message、message handler、uptime 都存放在一个信封对象中,然后将该信封添加到 mMessageEnvelopes 中。
这里还涉及另外一个成员变量:mSendingMessage,用以标记当前是否正在 handleMessage() 处理消息。当该函数执行的时候,mSendingMessage 被置 true,标记正在处理,在处理函数完成之后会将其再次置 false。
4. LooperCallback 类
system/core/libutils/include/utils/Looper.h
class LooperCallback : public virtual RefBase {
protected:
virtual ~LooperCallback();
public:
/**
* Handles a poll event for the given file descriptor.
* It is given the file descriptor it is associated with,
* a bitmask of the poll events that were triggered (typically EVENT_INPUT),
* and the data pointer that was originally supplied.
*
* Implementations should return 1 to continue receiving callbacks, or 0
* to have this file descriptor and callback unregistered from the looper.
*/
virtual int handleEvent(int fd, int events, void* data) = 0;
};
该类用以处理通过 addFd() 添加监听的 fd。在 addFd() 函数中会同步指定 callback,就是这里的 LooperCallback 对象。
4.1 addFd()
在 Looper.h 中可以看到该函数的声明:
int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
system/core/libutils/Looper.cpp
int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : nullptr, data);
}
int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
if (!callback.get()) {
if (! mAllowNonCallbacks) {
ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
return -1;
}
if (ident < 0) {
ALOGE("Invalid attempt to set NULL callback with ident < 0.");
return -1;
}
} else {
ident = POLL_CALLBACK;
}
{ // acquire lock
AutoMutex _l(mLock);
Request request;
request.fd = fd;
request.ident = ident;
request.events = events;
request.seq = mNextRequestSeq++;
request.callback = callback;
request.data = data;
if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
struct epoll_event eventItem;
request.initEventItem(&eventItem);
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex < 0) {
int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
if (epollResult < 0) {
ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
return -1;
}
mRequests.add(fd, request);
} else {
int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
if (epollResult < 0) {
if (errno == ENOENT) {
epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
if (epollResult < 0) {
ALOGE("Error modifying or adding epoll events for fd %d: %s",
fd, strerror(errno));
return -1;
}
scheduleEpollRebuildLocked();
} else {
ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
return -1;
}
}
mRequests.replaceValueAt(requestIndex, request);
}
} // release lock
return 1;
}
这里涉及到 Looper 中的另外一个成员变量:mRequests,这是一个KeyedVector 类型的变量,用以存放通过 addFd() 添加的监听请求。
如代码所示,首先确认 mRequests 中是否已经存放该 fd 的监听,如果没有,则通过 epoll_ctl() 将对该 fd 的监听添加到 epoll 中,并将此次的请求添加到 mRequests 中;如果已经存在对该 fd 的监听,则对 epoll 进行更改,并将 mRequests 中的request 进行替换。
5. wake()
system/core/libutils/Looper.cpp
void Looper::wake() {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ wake", this);
#endif
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));
}
}
}
通过往 mWakeEventFd 中写个数据来达到唤醒的目的。
6.