Looper
Looper是Handler和Thread相關(guān)聯(lián)的橋梁,也是APP開發(fā)中線程間通信的用的最多的一個(gè).
然而使用率卻是異常的低下,因?yàn)樵谙蛑骶€程交互的時(shí)Looper該做的工作已經(jīng)做好,使用上只需要在主線程創(chuàng)建Handler對(duì)象,然后再需要的地方發(fā)送消息即可.
參考博客 Android 異步消息處理機(jī)制 讓你深入理解 Looper监署、Handler蝇狼、Message三者關(guān)系 洪洋
Looper的初始化創(chuàng)建
Looper和線程的關(guān)系是一一對(duì)應(yīng)的,每一個(gè)線程有且只有一個(gè)Looper,可以從Looper的使用中看出.
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));
}
在使用子線程中使用Hander時(shí),需要有Looper對(duì)象,而Looper的構(gòu)造函數(shù)是private修飾的,想要獲得創(chuàng)建一個(gè)Looper對(duì)象就只能調(diào)用靜態(tài)方法prepare.
在方法中我們可以看到調(diào)用了sThreadLocal.get()
方法,返回的若非空就會(huì)拋出異常.這里就限定了一個(gè)線程只能有一個(gè)Looper.
Looper的構(gòu)造函數(shù)
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在構(gòu)造函數(shù)中創(chuàng)建了一個(gè)MessageQueue(消息隊(duì)列).
Looper的使用
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();
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(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();
}
}
當(dāng)操作完成就可以調(diào)用Looper.loop();從代碼中可以看出在通過(guò)myLooper中拿到了當(dāng)前線程的Looper對(duì)象,獲取了對(duì)應(yīng)的MessageQueue之后,該線程會(huì)執(zhí)行一個(gè)死循環(huán),在死循環(huán)中不停的讀取MessageQueue隊(duì)列中的Message并調(diào)用 msg.target.dispatchMessage(msg);去處理該消息.
Handler
在使用Handler時(shí),我們通常都是實(shí)例化一個(gè)對(duì)象去發(fā)送消息,然后在handleMessage方法中去處理對(duì)應(yīng)的消息,并作出對(duì)應(yīng)的處理.
Hanlder的初始化
public Handler() {
this(null, false);
}
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;
}
在初始化中我們看到了Handler將自己和Looper進(jìn)行了關(guān)聯(lián),如若在子線程中未創(chuàng)建Looper就創(chuàng)建Hanlder那么便會(huì)拋出異常.并且在下面繼續(xù)獲取了Looper的消息隊(duì)列.
Handler的使用
Message message = Message.obtain();
message.what = TEXT;
message.obj = (int) (Math.random() * 1000);
mHandler.sendMessage(message);
Handler使用方式十分之簡(jiǎn)單,在需要使用的地方發(fā)送一個(gè)Message消息即可,在創(chuàng)建Handler時(shí)重寫handleMessage方法中處理對(duì)應(yīng)的Message消息即可.
多數(shù)人走到這一步就停下了,因?yàn)橐呀?jīng)知道如何使用Hanlder和Looper了,能滿足跨線程交互需求了,也就沒(méi)有繼續(xù)探索的愿望了,然后在面試的一個(gè)一問(wèn)Handler為什么能切換到主線程去執(zhí)行對(duì)應(yīng)的方法就懵逼了(面試問(wèn)懵逼好幾個(gè)了....)
Handler跨線程的原因
既然發(fā)送消息是在子線程,在handleMessage中處理的時(shí)候已經(jīng)到了主線程,那么線程切換的奧秘一定就在這兩個(gè)方法調(diào)用過(guò)程中,我們就從sendMessage方法中一步一步往下看.
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
到這里就可以看出一點(diǎn)端倪了,mQueue出現(xiàn)了,也就是Handler在創(chuàng)建時(shí)獲取的Looper的MessageQueue對(duì)象.
我們繼續(xù)向下看
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在這里我們又看到了一點(diǎn)意思的東西,msg.target = this
在Looper.loop中我們看到msg.target.dispatchMessage(msg);
這么一行代碼,現(xiàn)在稍微一推敲就知道最終發(fā)生了什么,怎么切換線程的,但是我們還是繼續(xù)往下看.
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;
}
恩,到這里就是將Message加入到消息隊(duì)列中去中去,hanlder中消息發(fā)送流程已經(jīng)走完了.
在這里handler將Message加入到了消息隊(duì)列中,而Looper一直線主線程中阻塞著,所以一收到消息就拿到了Message對(duì)象,然后在主線程中調(diào)用了Hanlder的處理方法.
Looper對(duì)消息的處理
從上面的分析已經(jīng)了解到了子線程和主線程是如何切換的,我們繼續(xù)看在主線程中Looper是如何處理發(fā)送過(guò)來(lái)的消息的.
// Looper.loop();中代碼
Message msg = queue.next(); // might block
// MessageQueue中next();代碼
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;
}
}
瞧,我們發(fā)現(xiàn)了什么,又是一個(gè)死循環(huán)阻塞,原來(lái)主線程不是阻塞在Looper中,而是阻塞在MessageQueue對(duì)象中.
可以看到當(dāng)消息隊(duì)列有消息的時(shí)候立馬返回消息,沒(méi)有消息就阻塞(我就偷了個(gè)懶,不在繼續(xù)深入MessageQueue的原理了...)
Looper收到返回的消息會(huì)調(diào)用msg.target.dispatchMessage(msg)去處理,也就是調(diào)用Handler去處理.
我們繼續(xù)來(lái)到Hanlder的處理方法中.
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
msg.callback我們先放一放,就我們普通發(fā)送的Message通常是沒(méi)有callback對(duì)象的,下面的mCallback我們來(lái)看一看,該對(duì)象出現(xiàn)在構(gòu)造函數(shù)之中,通過(guò)構(gòu)造函數(shù)來(lái)賦值,我們來(lái)看看這個(gè)對(duì)象的定義
public interface Callback {
public boolean handleMessage(Message msg);
}
可以看出就是一個(gè)接口,和自己重寫handleMessage一樣,只不過(guò)提供另一種方式來(lái)處理.(說(shuō)實(shí)話,在成員對(duì)象創(chuàng)建上面還重寫其方法,我感覺(jué)是看著挺難受的,這樣抽取成對(duì)象,然后通過(guò)構(gòu)造函數(shù)傳遞進(jìn)去,看著舒服多了.)
回到正題中來(lái),我們還剩下一個(gè)Messaged的callBack對(duì)象沒(méi)整明白.
首先,我們來(lái)看一看這究竟是一個(gè)什么對(duì)象.
/*package*/ Runnable callback;
可以看到就是一個(gè)任務(wù)而已,而handleCallback(msg)方法點(diǎn)進(jìn)去再來(lái)看一看
private static void handleCallback(Message message) {
message.callback.run();
}
只是單純的是運(yùn)行這個(gè)任務(wù)而已,但是這個(gè)任務(wù)是哪里來(lái)的呢?
答案在Handler,Handler不僅可以發(fā)消息給自己在主線程處理,也可以直接發(fā)送一個(gè)任務(wù)去主線程運(yùn)行.
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
到這里也就看明白了,剩下就和普通消息一樣的處理方式了.
文章到此結(jié)束,順便給自己打個(gè)小廣告,深圳求職,目前在職招人頂缸中(ps:找個(gè)人頂缸真不好招...全是假簡(jiǎn)歷)
簡(jiǎn)歷戳我