2015-01-18 12:00
在android中做延時(shí)處理一般用handler.postDelayed()和view.postDelayed(action,delay)來實(shí)現(xiàn)懊蒸,view.postDelayed也是通過handlder.postDelayed來實(shí)現(xiàn)的竿裂,不過有一些特殊處理的地方睛廊。
handler.postDelayed
handler處理延時(shí)邏輯是通過發(fā)送延時(shí)消息來處理的
//source
public final boolean postDelayed(Runnable r, long delayMillis){
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
sendMessageDelayed:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
sendMessageAtTime:
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);
}
將延時(shí)消息放入到消息隊(duì)列中。SystemClock.uptimeMillis()是開機(jī)到現(xiàn)在的時(shí)間(毫秒)拆讯,不包括睡眠的時(shí)間筛圆。不用System.currentTimeMillis()的原因是System.currentTimeMillis()的時(shí)間是可以被System.setCurrentTimeMillis修改的决摧,如果被修改了則發(fā)生難以想象的后果政基。
enqueueMessage調(diào)用MessageQueue.enqueueMessage(msg,uptimeMillis)
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
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;
}
此處會(huì)將傳入的消息對(duì)象根據(jù)觸發(fā)時(shí)間(when)插入到message queue中。然后判斷是否要喚醒等待中的隊(duì)列胜蛉。
. 如果插在隊(duì)列中間挠进。說明該消息不需要馬上處理,不需要由這個(gè)消息來喚醒隊(duì)列誊册。
. 如果插在隊(duì)列頭部(或者when=0)领突,則表明要馬上處理這個(gè)消息。如果當(dāng)前隊(duì)列正在堵塞案怯,則需要喚醒它進(jìn)行處理君旦。
通過nativeWake方法喚醒隊(duì)列。
looper執(zhí)行MessageQueue中的消息:
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
...
}
msg.recycleUnchecked();
}
}
只是調(diào)用了MessageQueue.next()方法嘲碱〗鹂常可能會(huì)阻塞。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
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;
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());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 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 {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// 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.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// 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.
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) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// 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;
}
}
該方法會(huì)先調(diào)用nativePollOnce阻塞麦锯,然后進(jìn)入死循環(huán)捞魁。nativePollOnce()的作用類似與object.wait(),使用了native方法來對(duì)線程進(jìn)行精確時(shí)間的喚醒离咐,
如果head Message是有延遲而且延遲時(shí)間沒到的(now < msg.when),計(jì)算下時(shí)間間隔(nextPollTimeoutMillis),設(shè)置timeout為兩者之差宵蛀,進(jìn)入下一次循環(huán)昆著。
如果Message無延時(shí)或已到達(dá)執(zhí)行時(shí)間,則直接返回該Message.
如果當(dāng)前的Message阻塞住了MessageQueue(pendingIdleHandlerCount <= 0)术陶,把全局變量mBlocked改為true凑懂,在下一個(gè)Message放入隊(duì)時(shí)會(huì)判斷這個(gè)message的位置。如果在queue的頭部梧宫,則用nativeWake喚醒線程接谨。
總結(jié):[msg loop] -->調(diào)用MessageQueue.next(),若頭部的消息需要被執(zhí)行在返回該消息,send該消息之后繼續(xù)調(diào)用next方法獲取下一個(gè)消息塘匣,若頭部的不需要被執(zhí)行則阻塞住隊(duì)列脓豪,若有等待執(zhí)行的Message,計(jì)算一下剩余時(shí)間,繼續(xù)調(diào)用nativePollOnce()阻塞,無限循環(huán)到阻塞時(shí)間到或者下一次有Message進(jìn)隊(duì)忌卤。下個(gè)消息進(jìn)隊(duì)時(shí)若不需要延時(shí)在放在Queue的頭部扫夜,否則在放在Queue的中部。
view.postDelayed
view的延時(shí)也是調(diào)用了handler的postDelayed.
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().postDelayed(action, delayMillis);
return true;
}
若view的AttachInfo不為空驰徊,則調(diào)用AttachInfo中的handler的postDelayed笤闯。若AttachInfo為空,則先將action放入RunQueue中棍厂。RunQueue為HandlerActionQueue颗味,用來存放view沒有handler時(shí)的action。
執(zhí)行action:
public void executeActions(Handler handler) {
synchronized (this) {
final HandlerAction[] actions = mActions;
for (int i = 0, count = mCount; i < count; i++) {
final HandlerAction handlerAction = actions[i];
handler.postDelayed(handlerAction.action, handlerAction.delay);
}
mActions = null;
mCount = 0;
}
}
還是需要傳入一個(gè)Handler牺弹,利用handler來執(zhí)行action浦马。當(dāng)view被關(guān)聯(lián)到window時(shí),會(huì)執(zhí)行該隊(duì)列中的Action.
AttachInfo是View的一個(gè)附加信息存儲(chǔ)類例驹,當(dāng)view被關(guān)聯(lián)到window時(shí)會(huì)被賦值捐韩。