一、Looper模型建立
當(dāng)一個(gè)線程在run方法調(diào)用Looper的以下操作后
Looper.prepare()
Looper.loop()
Looper/Handler的模型就建立起來(lái)了
這里需要注意是在 MessageQueue.next()函數(shù)中
int nextPollTimeoutMillis = 0;
for (;;) {
nativePollOnce(ptr, nextPollTimeoutMillis);
...
第一次進(jìn)去傳入到epoll_wait的timeout為0,也就是說(shuō)立馬返回POLL_TIMEOUT。
pollInner中會(huì)返回epoll喚醒的原因, 默認(rèn)有如下幾種情況
- POLL_WAKE = -1
默認(rèn)情況 - POLL_ERROR = -2
epoll_wait返回錯(cuò)誤 - POLL_TIMEOUT = -3
epoll是因?yàn)槌瑫r(shí)喚醒 - POLL_CALLBACK = -4
epoll喚醒是有具體的事件發(fā)生
pollInner在epoll喚醒后會(huì)根據(jù)喚醒原因決定是否需要繼續(xù) epoll_wait, 在上述的情況下pollInner會(huì)返回,進(jìn)而 java 層的nativePollOnce也就返回了。
java層的next在nativePollOnce后發(fā)現(xiàn)并沒(méi)有Message,所以此時(shí)計(jì)算得到 nextPollTimeoutMillis = -1
, 然后再次觸發(fā) nativePollOnce,會(huì)造成epoll_wait無(wú)限的等待下去。
二、Java層發(fā)送Message
線程在建立起Looper模型后,就可以往Handler發(fā)送Message了。
Handler調(diào)用sendMessage最終都是通過(guò)
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; //設(shè)置target Handler
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
if (mQuitting) { //是否正在退出
msg.recycle();
return false;
}
msg.markInUse(); //標(biāo)記當(dāng)前Message正在使用
msg.when = when; //什么時(shí)候發(fā)生
Message p = mMessages; //獲得 Message 頭部節(jié)點(diǎn)
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//第一個(gè)節(jié)點(diǎn)
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked; //mBlocked在沒(méi)有消息處理時(shí)都為true
} 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;
//將當(dāng)前Message按照when時(shí)間插入到對(duì)應(yīng)位置
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;
}
Handler發(fā)送消息,主要是將消息保存到 mMessages中,注意 Message本身是一個(gè)單身鏈表,當(dāng)mMessages里的消息是按照被調(diào)用處理的時(shí)間排序的,從小到大,也就是排在最前的消息優(yōu)先被處理。
當(dāng)消息被插入時(shí),然后根據(jù)當(dāng)前情況(mBlocked)來(lái)決定是否需要喚醒epoll
如圖所示
- java層首先將Message按照時(shí)間順序保存到mMessages中
- 然后調(diào)用nativeWake去喚醒epoll, (前提是當(dāng)前是IDLE的狀態(tài))
喚醒的方法其實(shí)很簡(jiǎn)單就是往mWakeFd時(shí)寫(xiě)入一些數(shù)據(jù),然后Epoll就監(jiān)聽(tīng)到了mWakeFd事件
- 然后調(diào)用nativeWake去喚醒epoll, (前提是當(dāng)前是IDLE的狀態(tài))
- epoll在被喚醒后 依次遍歷 native MessageEnvelopes. 以及一些LooperCalllback的callbacks
- pollInner返回 -> nativePollOnce返回,
- Looper.loop獲得MessageQueue的Message,然后dispatchMessage.
三、Native 發(fā)送消息
從前面第二小節(jié)可以看出,epoll在被喚醒后,會(huì)先依次處理 native的 MessageEnvelopes里的消息。 現(xiàn)在來(lái)看下 native MessageEnvelopes是怎么構(gòu)建的。
在Looper.cpp里支持多種sendMessage形式的消息發(fā)送,但是最終都是調(diào)用到 sendMessageAtTime()這個(gè)函數(shù)
void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
const Message& message) {
size_t i = 0;
{ // acquire lock
AutoMutex _l(mLock);
//按照時(shí)間順序插入到 mMessageEnvelopes中
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);
if (mSendingMessage) {
return;
}
} // release lock
// Wake the poll loop only when we enqueue a new message at the head.
if (i == 0) {
wake();
}
}
從上面可以看出, native也是支持Looper/Handler消息模型的,具體的用法可以參考 SurfaceFlinger里面的 dispatchRefresh 方法
http://androidxref.com/8.0.0_r4/xref/frameworks/native/services/surfaceflinger/MessageQueue.cpp#51
如圖所示
- 先向 mMessageEnvelopes 中按照時(shí)間順序插入Message
- 如果mMessageEnvelopes里沒(méi)有消息,當(dāng)前插入的是第一個(gè),則調(diào)用wake喚醒 epoll
- epoll在喚醒后,會(huì)遍歷 mMessageEnvelopes里的消息,依次處理。
這里需要注意:
只有當(dāng)前的Message是第一個(gè)時(shí)才調(diào)用wake,而非第一個(gè),則不會(huì)喚醒。這個(gè)是什么原因呢??? 如果當(dāng)前插入的message沒(méi)有delay時(shí),豈不時(shí)會(huì)有delay???
四、addFd
由前面可知,Looper/Handler的模型主要是依靠不斷的喚醒epoll來(lái)實(shí)現(xiàn)的,主要的手段是喚醒 mWakeFd, 或者是epoll的timeout, timeout手段主要是針對(duì) sendMessageDelayed()這樣的函數(shù)。
其實(shí) epoll 的喚醒除了 mWakeFd的喚醒和epoll的timeout外,還支持監(jiān)聽(tīng)其它事件。
主要是通過(guò)Looper::addFd來(lái)實(shí)現(xiàn)的。
int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
}
int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
...
{ // acquire lock
AutoMutex _l(mLock);
Request request; //創(chuàng)建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; //創(chuàng)建epoll_event
request.initEventItem(&eventItem);
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex < 0) {
int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
...
mRequests.add(fd, request); //將Request加入到mRequests中
....
}
從上面的代碼可以看出addFd就是創(chuàng)建一個(gè)Request,并添加到epoll監(jiān)聽(tīng)池中,并插入到mRequests中。
其中調(diào)用到addFd的可以是native的code, 也可以java層的代碼,流程如下
- native層addFd 監(jiān)聽(tīng) fd1
- java層通過(guò)MessageQueue調(diào)用nativeSetFileDescriptorEvents去監(jiān)聽(tīng) fd2
- 當(dāng)fd1和fd2分別有事件發(fā)生時(shí),此時(shí)epoll將被被喚醒
- epoll檢測(cè)出來(lái)發(fā)現(xiàn)是fd1, fd2事件發(fā)生了,
- 然后將它們作為Response放入到mResponses中,
- 針對(duì)fd1, 調(diào)用 LooperCallback里的handleEvent事件
- 針對(duì)fd2, 調(diào)用到Java層的handleEvent()
五、Messenger
Messenger是AIDL和Handler的結(jié)合體,所以如果事先不了解AIDL的話,直接去學(xué)習(xí)Messenger就會(huì)覺(jué)得比較卡。
Messenger是AIDL的封裝,底層是通過(guò)AIDL進(jìn)行跨進(jìn)程通信,只不過(guò)可以不用像AIDL那樣定義AIDL這么麻煩,Messenger直接使用IMessenger.aidl,不通的消息可以通過(guò)Message.what來(lái)區(qū)分,這樣會(huì)比較簡(jiǎn)單。注意: Messenger服務(wù)端的的處理是放在一個(gè)線程里的,而不是在binder線程中操作的,原理很簡(jiǎn)單,就是在binder線程中,將Message發(fā)送給Handler所在的線程。
注意, 這里的Handler線程并不一定是在UI線程中(大多數(shù)情況是在UI線程中), 可以是自己定義的非UI線程里的Handler, (如HandlerThread.getLooper())
Messenager和AIDL相比較,
- Messenager很簡(jiǎn)單,不用自定義AIDL, 它可以通過(guò)Message.what來(lái)區(qū)分不同的消息。
- Messenager將所有的消息都route到一個(gè)線程中操作,這里不用考慮同步的需求。而AIDL收到的消息都是在binder線程中,如果想在binder線程中操作,勢(shì)必會(huì)考慮同步的問(wèn)題
六、 小結(jié)
一般App開(kāi)發(fā)主要只用到Handler/Looper的Message處理,但是其實(shí)Handler/Looper的功能遠(yuǎn)大于此, 支持jni層的Message, 支持fd 監(jiān)聽(tīng)
它們的處理順序如下
Jni Messages -> fd event -> Java Message