IdleHandler是什么?
/**
* Callback interface for discovering when a thread is going to block
* waiting for more messages.
*/
public static interface IdleHandler {
/**
* Called when the message queue has run out of messages and will now
* wait for more. Return true to keep your idle handler active, false
* to have it removed. This may be called if there are still messages
* pending in the queue, but they are all scheduled to be dispatched
* after the current time.
*/
boolean queueIdle();
}
IdleHandler是定義在MessageQueue里面的一個(gè)Interface,它在當(dāng)線程開始阻塞等待消息的時(shí)候會調(diào)用的一個(gè)接口;當(dāng)消息隊(duì)列中的消息已用完或著等待更多消息時(shí)調(diào)用。返回true以保持IdleHandler處于活動狀態(tài),返回false以將其刪除。如果隊(duì)列中仍有掛起的消息,則可以調(diào)用此命令,但這些消息都計(jì)劃在當(dāng)前時(shí)間之后發(fā)送。
IdleHandler使用方法
//我們在子線程開啟一個(gè)Looper
Handler mHandler;
new Thread(){
@Override
public void run(){
//初始化Looper
Looper.prepare();
//創(chuàng)建Handler
mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.i("TAG","接收線程:"+Thread.currentThread().getId()+"收到Message");
}
};
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
//當(dāng)前線程如果Looper獲取消息處于阻塞狀態(tài)會調(diào)用該方法
Log.i("TAG","運(yùn)行IdleHandler");
//返回true說明重復(fù)使用IdleHandler
//返回false則使用后刪除該IdleHandler
return true;
}
});
//開始循環(huán)讀取消息
Looper.loop();
}
}.start()
//然后我們開始發(fā)送1秒間隔Message
for (int i = 0 ; i < 5 ; i++){
//每個(gè)消息間隔1000ms
mHandler.sendMessageDelayed(Message.obtain(),1000*i);
}
//打印日志如下,間隔1000ms之間會執(zhí)行IdleHandler的邏輯
I/TAG: 接收線程:4660收到Message
I/TAG: 運(yùn)行IdleHandler
I/TAG: 接收線程:4660收到Message
I/TAG: 運(yùn)行IdleHandler
I/TAG: 接收線程:4660收到Message
I/TAG: 運(yùn)行IdleHandler
I/TAG: 接收線程:4660收到Message
I/TAG: 運(yùn)行IdleHandler
I/TAG: 接收線程:4660收到Message
I/TAG: 運(yùn)行IdleHandler
根據(jù)上面例子看出,發(fā)送的Message直接的間隔為1000ms,意味著在MessageQueue#next()獲取每個(gè)Message之間,會阻塞1000ms,而在這1000ms就會調(diào)用IdleHandler,現(xiàn)在我們分析下源碼,IdleHandler是怎么被調(diào)用的
//MessageQueue.java
//存放IdleHandler
private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
//添加IdleHandler
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
//移除IdleHandler
public void removeIdleHandler(@NonNull IdleHandler handler) {
synchronized (this) {
mIdleHandlers.remove(handler);
}
}
//調(diào)用IdleHandler
Message next() {
//...省略部分代碼
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
//開始循環(huán)找出下個(gè)執(zhí)行Message
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//下面代碼作用是如果存在同步屏障則找出異步Message
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
//一般為同步消息,isAsynchronous = false
}
if (msg != null) {
//Message對象不為空
if (now < msg.when) {
//當(dāng)前時(shí)間小于Message的執(zhí)行時(shí)間
// Next message is not ready. Set a timeout to wake up when it is ready.
//計(jì)算出需要睡眠的時(shí)間
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
//否則返回Message對象
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
//沒有可執(zhí)行的Message對象
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
//只有當(dāng)沒有可執(zhí)行Message或者M(jìn)essage對象執(zhí)行時(shí)間需要等待時(shí),才會走下面代碼
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
//第一次循環(huán),記錄IdleHadnler的數(shù)量
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
//如果不存在IdleHandler,則跳出本次循環(huán)
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
//開始循環(huán)執(zhí)行IdleHandler
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
//如IdleHandler返回false,則移除IderHandler
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// 重制pendingIdleHandlerCount = 0,這個(gè)變量在循環(huán)讀取Message隊(duì)列之前是被初始化為-1,所以在第二次循環(huán)和之后,在上面邏輯會直接跳出本次循環(huán)
//if (pendingIdleHandlerCount <= 0) {
// //如果不存在IdleHandler,則跳出本次循環(huán)
// // No idle handlers to run. Loop and wait some more.
// mBlocked = true;
// continue;
//}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
總結(jié)
IdleHandler會在Looper.loop()的MessageQueue.next()獲取消息的時(shí)候,如果消息隊(duì)列為空,或者消息隊(duì)列中下個(gè)可執(zhí)行的Message需要等待,則會循環(huán)遍歷且執(zhí)行MessageQueue中的mIdleHandler集合,而且只會在next()方法中,遍歷消息隊(duì)列的第一次得到執(zhí)行;