??我們知道調(diào)用handler.removeCallbacksAndMessages(null);可以清空當(dāng)前handler的所有回調(diào)和所有消息事示。想當(dāng)然的認(rèn)為handler.removeCallbacks(null)可以清空所有回調(diào),實則不然渴庆。本文旨在探明其原因康辑。
??首先,打開Handler.java,removeCallbacksAndMessages方法如下:
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
public final void removeCallbacksAndMessages(Object token) {
mQueue.removeCallbacksAndMessages(this, token);
}
??可以看到蕾羊,注釋中有提到參數(shù)為null時會移除所有回調(diào)和message,再看removeCallbacks方法帽驯,注釋中并沒有提到參數(shù)為null時會移除所有回調(diào)龟再。
/**
* Remove any pending posts of Runnable r that are in the message queue.
*/
public final void removeCallbacks(Runnable r)
{
mQueue.removeMessages(this, r, null);
}
??如果還不確信的話,我們可以繼續(xù)向下探究尼变。上文可以看到無論是在removeCallbacksAndMessages方法還是removeCallbacks方法中都繼續(xù)調(diào)用了mQueue對象中的removeCallbacksAndMessages和removeMessages方法吸申,mQueue對象是MessageQueue類的實例,打開MessageQueue.java文件找到這兩個方法享甸。首先是removeCallbacksAndMessages:
void removeCallbacksAndMessages(Handler h, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
??從該方法可以看出截碴,當(dāng)傳入的object對象為null時,會循環(huán)回收掉所有message蛉威。在看removeMessages方法日丹,當(dāng)傳入的Runnable為null時,會直接退出蚯嫌,該方法如下:
void removeMessages(Handler h, Runnable r, Object object) {
if (h == null || r == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.callback == r
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.callback == r
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
??所以handler.removeCallbacks(null)不會移除任何回調(diào)哲虾。