[Android] Handler中的IdleHandler
抛出
Handler
中的IdleHandler
- 它有什么能力?
- 它有什么用处?
- 能想到一些合适的场景吗?
Answer1:
首先看下源码的注释
/**
* 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();
}
注释中明确的指出当消息队列空闲时会执行IdelHandler
的queueIdle()
方法,该方法返回一个boolean
值, 如果为false
则执行完毕之后移除这条消息, 如果为true
则保留,等到下次空闲时会再次执行,
下面看下MessageQueue
的next()
方法可以发现确实是这样。
Message next() {
......
for (;;) {
......
synchronized (this) {
// 此处为正常消息队列的处理
......
if (mQuitting) {
dispose();
return null;
}
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount