android源碼解析-異步消息
android異步消息中我們常用的就是如下方式
先創(chuàng)建一個handler實例:
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//處理message返回結(jié)果
};
接著開啟一個線程:
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(2);
}
}).start();
我們執(zhí)行了handler.sendEmptyMessage();
方法,但是在主線程接到了返回結(jié)果,下面我們來探究一下原因.
原因探究
我們先看Handler.class
的構(gòu)造方法
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;
}
構(gòu)造方法創(chuàng)建了Looper的實例和MessageQueue的引用對象.創(chuàng)建了Looper的實例也就找到了線程對應(yīng)的looper和MessageQueue,因為一個MessageQueue對應(yīng)的只有一個Looper.中間有一句mLooper = Looper.myLooper();
我們稍后再看.
接下來看Handler調(diào)用的sendMessage方法。你會發(fā)現(xiàn)所有的方法調(diào)用的都是sendMessageAtTime()
方法管跺,那我們就看一下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);
}
Handler的sendMessageAtTime()
調(diào)用了queue.enqueueMessage()
方法也就是messageQueue的入隊方法垮兑。
我們看一下enqueueMessage:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
我們看到handler把自己的實例放進了msg的target這個到后邊會用到,接下來看MessageQueue類的enqueueMessage()
方法:
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;
}
里邊的for循環(huán)就是把消息放到messagequeue里的方法,根據(jù)when時間順序.
至此handler就把sendmessage中的message發(fā)送到messagequeue中.其中判斷了之前我們定義到msg里的handler實例.
那么MessageQueue是在哪里維護的呢?
看上邊的Handler構(gòu)造方法我們發(fā)現(xiàn)mQueue = mLooper.mQueue;
這個行代碼.
也就是說MessageQueue是在Looper維護的.
首先看一下Looper.prepare()
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));
}
再看一下構(gòu)造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
實際上在子線程必須執(zhí)行Looper.prepare()
是因為需要通過sThreadLocal.set(new Looper(quitAllowed));
建立Lopper與sThreadLocal的關(guān)系.我們再回看Handler的構(gòu)造方法mLooper = Looper.myLooper();
這個方法.
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
我們看到直接return了sThreadLocal.get()
這就說明了為什么要執(zhí)行Looper.prepare()
,因為需要先建立和sThreadLocal的關(guān)系.
接下來看 Looper.loop();
方法是執(zhí)行從enqueueMessage取出消息.
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();
}
}
有一個死循環(huán)執(zhí)行queue.next()
方法.如果有消息就繼續(xù)執(zhí)行.然后執(zhí)行消息分發(fā)msg.target.dispatchMessage(msg);
,可以看到msg.target
就是我們最開始在enqueueMessage步驟把handler.如果沒消息就休息等待.
下面看一下dispatchMessage:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
最后分發(fā)完方法后執(zhí)行了handleMessage回調(diào)方法.handleMessage方法我們再熟悉不過了.就是我們new Handler創(chuàng)建的回調(diào).
總結(jié)
Handler通過初始化創(chuàng)建了Looper和實例化了MessageQueue,Looper創(chuàng)建的時候需要先執(zhí)行Looper.propar()
,通過handler構(gòu)造方法匹配了本地ThreadLocal和線程-Looper-MessageQueue三者的對應(yīng)關(guān)系.
handler通過sendMessage方法執(zhí)行MessageQueue的enqueueMessage()
方法,實現(xiàn)了往MessageQueue插入消息.
由Looper.loop()
方法從MessageQueue中取出消息.由for循環(huán)執(zhí)行queue.next()
方法,然后執(zhí)行Handler的消息分發(fā)msg.target.dispatchMessage(msg);
,也就是我們new Handler的回調(diào)方法.
一些題外話
android中啟動關(guān)于線程和線程間通信的方法有很多,萬變不離其宗,這里就簡單的講下:
1.關(guān)于Handler.post()
(1)Handler.post();
,這個方法的常用場景是我們在子線程完成,子線程中,調(diào)用post()
方法后可以再方法內(nèi)寫ui操作的東西,,切記不要在子線程實例化的Handler執(zhí)行post()
再操作UI,舉個例子在其他子線程1實例化的Handler,在子線程2執(zhí)行post()
操作ui,那么還會報錯告訴你"工作線程不能操作UI"的錯誤.
(2)這個方法的實現(xiàn)原理并不是新開啟線程或者怎么樣,原理還是異步消息,把Handler封裝到Message里作為傳遞然后跨線程執(zhí)行.具體請看源碼,由于不太復(fù)雜們這里就不貼了.
2.關(guān)于HandlerThread
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Handler handler_thread = new Handler(handlerThread.getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//線程內(nèi)耗時操作
return false;
}
});
handler_thread.sendEmptyMessage();
源碼解析
(1)當(dāng)執(zhí)行handlerThread.start();
方法時候,執(zhí)行了HandlerThread
的run()
方法,里邊執(zhí)行了Looper.prepare();
和Looper.loop();
,又是熟悉的配方.在這一步建立了Looper/MessageQueue/threadLocal之前的關(guān)系,并且執(zhí)行了Looper.loop()
方法川队,線程處于阻塞狀態(tài)力细。當(dāng)我們發(fā)送一個消息的時候就會被執(zhí)行。
3.關(guān)于IntentService:
(1)繼承自Service固额,它可以理解為就是一個Service眠蚂,只不過融合了HandlerThread。
(2)繼承IntentService創(chuàng)建自己的服務(wù)的時候會重寫onHandleIntent()
方法斗躏,因為這個方法就是在IntentService源碼中Handler的handleMessage()
里實現(xiàn)的方法逝慧。
(3)源碼在onCreate()
中實現(xiàn)了HandlerThread并且執(zhí)行了start方法,然后new了ServiceHandler對象。
(4)在onStart()
中發(fā)送消息笛臣。
(5)在onStartCommand()
中調(diào)用了onStart()
方法栅干。
(6)總結(jié):這樣整個過程就通了,onCreate()
創(chuàng)建HandlerThread捐祠,每次啟動服務(wù)都會調(diào)用onStartCommand()
也就實現(xiàn)了發(fā)送消息碱鳞。然后onHandleIntent()
回調(diào)處理線程耗時操作。