Handler 核心知識(shí)點(diǎn)
1.為什么在不能再子線程直接初始化handler,主線程卻可以?
查看handler的源碼會(huì)發(fā)現(xiàn)
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
,在創(chuàng)建handler的時(shí)候,會(huì)檢查looper對(duì)象,如果為空,會(huì)拋出一個(gè)運(yùn)行時(shí)異常,也就是說,在子線程創(chuàng)建handler的時(shí)候,looper是沒有創(chuàng)建的,這也就解釋了,在子線程創(chuàng)建handler的時(shí)候需要 執(zhí)行如下代碼:
Looper.prepare();
...
Loop.loop();
為什么主線程不需要呢?
需要看那一下ActivityThread 這個(gè)類,ActivityThread就是我們常說的主線程或UI線程,ActivityThread的main方法是整個(gè)APP的入口!可以看看在這個(gè)類中,main函數(shù)中做了什么操作
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
不懂沒關(guān)細(xì),只需要看下咱們關(guān)心的內(nèi)容就可以了, == Looper.prepareMainLooper();== 以及 ==Looper.loop();==,這也就跟之前的對(duì)用上了,為什么在子線程的創(chuàng)建handler的時(shí)候需要 Looper.parpare(),以及Looper.loop(),而主線程不需要;其實(shí)在ActivityThread類中在main函數(shù)調(diào)用的prepareMainLooper()和在子線程中調(diào)用的parpare()還是略微有點(diǎn)區(qū)別,看源碼
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
代碼不懂沒關(guān)系,看注釋,大致意思就是:
==初始化當(dāng)前線程作為一個(gè)looper,讓它作為整個(gè)應(yīng)用的main looper,(個(gè)人理解,就是主線程吧),這個(gè) main looper 是有Android 環(huán)境創(chuàng)建的,因此你沒有必要調(diào)用你自己的方法 ,比如 prepare();==
很清晰了,也就解釋了為什么主線程不需要調(diào)用 prepare();
2.handler中延時(shí)消息是怎么實(shí)現(xiàn)的?
handler 中延時(shí)消息的發(fā)送時(shí)通過 ==postDelayed(Runnable r, Object token, long delayMillis)==實(shí)現(xiàn)的,但最終調(diào)用的==sendMessageAtTime(Message msg, long uptimeMillis)==函數(shù),然后加入到消息隊(duì)列中,到目前看沒有發(fā)現(xiàn)什么異常,可以看看,這個(gè)延時(shí)消息是怎么處理的!
handler 的中消息的分發(fā)處理是通過 Looper 中的loop()函數(shù)以及MessageQueue中的next()函數(shù)進(jìn)行處理的,可以先看loop()函數(shù):
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
代碼不少,沒有必要全部看明白,如果感覺不像是在這里處理的,那就看看,MessageQueuede next()函數(shù),
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);
}
沒有貼出全部代碼,可以看到,在這個(gè)方法內(nèi),如果頭部的這個(gè)Message是有延遲而且延遲時(shí)間沒到的(now < msg.when),會(huì)計(jì)算一下時(shí)間(保存為變量nextPollTimeoutMillis),然后在循環(huán)開始的時(shí)候判斷如果這個(gè)Message有延遲,就調(diào)用nativePollOnce(ptr, nextPollTimeoutMillis)進(jìn)行阻塞。nativePollOnce()的作用類似與object.wait(),只不過是使用了Native的方法對(duì)這個(gè)線程精確時(shí)間的喚醒。
3.handler MessageQueue是如何被阻塞的以及被喚醒的?
在MessageQueue的next函數(shù)中可以看到,里面不過是有一個(gè) for (;;) 死循環(huán)結(jié)果,循環(huán)體內(nèi)部調(diào)用了一個(gè) ==nativePollOnce(long, int)****== 方法。這是一個(gè) Native 方法,實(shí)際作用是通過 Native 層的 MessageQueue 阻塞當(dāng)前調(diào)用棧線程 nextPollTimeoutMillis 毫秒的時(shí)間。
==可以看到nextPollTimeoutMillis== 取值不同情況下的阻塞表現(xiàn)
-
小于 0
一直被阻塞,知道被喚醒
-
等于 0
不會(huì)被阻塞
-
大于 0
最長阻塞 nextPollTimeoutMillis 毫秒,期間如被喚醒會(huì)立即返回。
==nextPollTimeoutMillis==的默認(rèn)值為0,所以不會(huì)阻塞,會(huì)直接去取 Message 對(duì)象,如果沒有取到 Message 對(duì)象數(shù)據(jù),則直接會(huì)把 ==nextPollTimeoutMillis== 置為 -1,此時(shí)滿足小于 0 的條件,會(huì)被一直阻塞,直到其他地方調(diào)用另外一個(gè) Native 方法 nativeWake(long) 進(jìn)行喚醒 ,調(diào)用這個(gè)函數(shù)的地方是在 ==MessageQueue==中的 ==enqueueMessage== 中被調(diào)用的!
4.Lopper中的loop函數(shù)為什么不會(huì)阻塞主線程?
有上面ActivityThread的main函數(shù)中源碼可以知道,在程序啟動(dòng)的時(shí)候回初始化一個(gè)Looper,這個(gè)looper 就是一個(gè)main looper ,為什么說是main looper呢?因?yàn)檫@個(gè)lopper在應(yīng)用的整個(gè)生命周期中不是唯一,可以看看looper 的parpare函數(shù):
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
可以看到,只要調(diào)用這個(gè)函數(shù),就會(huì)新創(chuàng)建一個(gè)Looper 保存起來!至于為什么loop不會(huì)阻塞主線程,可以參考上面的內(nèi)容,在主線程的這個(gè)loop,如果有消息事件就處理,如果沒有就休眠,釋放cpu資源,等待下一次被喚醒!直至這個(gè)程序退出!