引言
Handler機(jī)制是Android消息機(jī)制置森,是非常重要的需要深刻認(rèn)識的基礎(chǔ)知識蛹尝,在日后的開發(fā)中需要被頻繁用到的知識鹅士。
Handler機(jī)制中涉及Handler 褥影,Looper丈冬,MessageQueue宪塔,Message
接下來就讓我們從整體到局部的逐個(gè)說明下他們的關(guān)系
整體架構(gòu)
Handler梢杭,MessageQueue偏窝,Message衬吆,Looper
四者之間的關(guān)系如下
Looper 是整體的老大梁钾,負(fù)責(zé)循環(huán)整個(gè)消息Message,MessageQueue則是Message的容器逊抡,而Handler不過是Android為了開發(fā)者封裝出來的一個(gè)用于消息創(chuàng)建姆泻,發(fā)送消息,消息事件回調(diào)的一個(gè)類冒嫡。
開始
我們從Android使用消息機(jī)制來說整個(gè)Handler機(jī)制的運(yùn)行過程拇勃。
如果所示表明了在main()
中開始了這一消息之旅孝凌,那么Looper.loop()
方法做了什么呢方咆,我們接著看源碼
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper(); //1
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; //2
// 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();
for (;;) { //3
Message msg = queue.next(); // might block //4
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg); //5
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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(); //6
}
}
Looper的looper()方法主要是注釋的6個(gè)點(diǎn)以下將逐一介紹
- 注釋1 中的
Looper me = myLooper()
這里是為了獲取到Looper這個(gè)對象,那我們?nèi)タ聪?myLooper()
方法到實(shí)現(xiàn) 如下
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
這里說明了是從sThreadLocal.get();
中獲取那么 這里的THreadLocal又是什么鬼?答:ThreadLocal是Java中用于對不同線程存儲變量的一個(gè)類蟀架,類似一個(gè)Map的存儲類(key為對應(yīng)對線程瓣赂,value為存儲的值),那么sThreadLocal是什么時(shí)候賦值的 在上圖中往上看可以看到在Looper.loop()
方法之前有調(diào)用Looper.prepareMainLooper();
這里就是對Looper進(jìn)行賦值,將當(dāng)前線程與Looper進(jìn)行綁定辜窑。內(nèi)部方法如下
/**
* 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();
}
}
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
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));
}
這樣就完成了Looper的綁定钩述。這里也說明了為什么在一個(gè)新的線程里為什么不調(diào)用Looper.prepare();直接使用Looper.loop()會crash,答案在如下代碼中(新的線程里沒有Looper所以肯定會報(bào)錯(cuò))
final Looper me = myLooper(); //1
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
- 注釋2 就是獲取當(dāng)前Looper的MessageQueue (稍后會講解這個(gè)類的作用)
- 注釋3 就開始Looper的死循環(huán) (這里為什么不會導(dǎo)致程序的ANR? 這里為什么會導(dǎo)致程序的ANR穆碎,要對ANR有一個(gè)詳細(xì)的了解牙勘,稍后會有一篇文章講解什么是ANR,為什么會一些操作導(dǎo)致ANR所禀,而不是什么死循環(huán)都會導(dǎo)致ANR)
- 注釋4 就是從MessageQueue中獲取對應(yīng)的下一個(gè)Message方面,這里注意到在源碼注釋上 有一句 // might block 意思是可能會阻塞 這里我們需要深入的去看下源碼 (這里的解釋就直接在代碼后面以注釋的形式進(jìn)行講解)
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 (;;) { //這里發(fā)現(xiàn)MessageQueue也是一個(gè)死循環(huán)
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//這是JNI的方法,在JNI層等待被調(diào)用喚醒 就是這里可能會導(dǎo)致阻塞色徘,因?yàn)樵贘NI層等待下一個(gè)消息
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; //獲取一個(gè)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());
}
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; //返回Message交給Looper處理
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
//如果沒有消息了則返回null,并退出
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.
//處理注冊的IdleHandler褂策,當(dāng)MessageQueue中沒有消息的時(shí)候横腿,Looper會調(diào)用IdleHandler進(jìn)行一些工作颓屑,例如垃圾回收等。
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;
}
}
- 注釋5 就是將當(dāng)前執(zhí)行的消息事件回調(diào)出去耿焊,這里target就是Handler揪惦。
- 注釋6 則是將當(dāng)前消息進(jìn)行回收
以上就是
Looper.loop();
方法的說明,也是Looper核心方法
接下來就是講一個(gè)Handler罗侯,Message器腋,MessageQueue類
Handler
Handler 我個(gè)人覺得它是Android給開發(fā)者的一個(gè)輔助類,它封裝了消息的投遞钩杰,消息處理回調(diào)
構(gòu)造函數(shù)(一切的開始)
public Handler() { this(null, false); }
public Handler(Callback callback) { this(callback, false); }
public Handler(Looper looper) { this(looper, null, false); }
public Handler(Looper looper, Callback callback) { this(looper, callback, false); }
public Handler(boolean async) { this(null, async); }
實(shí)現(xiàn)1
public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
實(shí)現(xiàn)2
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
最終都是調(diào)用了6纫塌,7這兩個(gè)就是將 mLooper,mQueue,mCallback,mAsynchronous 這四個(gè)賦值沒啥說的
Handler其他的方法就是 obtainMessage(),sendMessage(),dispatchMessage()
沒什么說的讲弄,大家看下源碼就可以了
Message
小弟一樣的角色措左,就是用來發(fā)送承載東西的類,也沒什么說的
MessageQueue消息隊(duì)列
消息隊(duì)列用于處理獲取消息和插入消息垂睬,整體是一個(gè)隊(duì)列的形式
題外話-Android為什么為我們提供HandlerThread媳荒?
是因?yàn)槲覀儗懖幻靼讍峥购罚坎?是Android考慮到我們寫的不夠周全