Android的Handler,Looper源码剖析
之前了解android的消息處理機(jī)制,但是源碼看的少,現(xiàn)在把Looper,Handler,Message這幾個(gè)類的源碼分析一哈
android的消息處理有三個(gè)核心類:Looper,Handler和Message。其實(shí)還有一個(gè)Message Queue(消息隊(duì)列),但是MQ被封裝到Looper里面了,我們不會(huì)直接與MQ打交道,因此我沒將其作為核心類
Looper源碼:
Looper的字面意思是“循環(huán)者”,它被設(shè)計(jì)用來(lái)使一個(gè)普通線程變成Looper線程。所謂Looper線程就是循環(huán)工作的線程。
使用Looper類創(chuàng)建Looper線程Demo:
public class LooperThread extends Thread {@Overridepublic void run() {// 將當(dāng)前線程初始化為L(zhǎng)ooper線程Looper.prepare();// ...其他處理,如實(shí)例化handler// 開始循環(huán)處理消息隊(duì)列Looper.loop();} } 1)Looper.prepare()源碼
public final class Looper {private static final String TAG = "Looper";// sThreadLocal.get() will return null unless you've called prepare()./*如果沒有調(diào)用prepare將Looper對(duì)象設(shè)置為線程的本地變量,則sThreadLocal.get()為空*//*// 每個(gè)線程中的Looper對(duì)象其實(shí)是一個(gè)ThreadLocal,即線程本地存儲(chǔ)(TLS)對(duì)象*/static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//當(dāng)前線程的本地變量private static Looper sMainLooper; // guarded by Looper.classfinal MessageQueue mQueue;//Looper維護(hù)的消息隊(duì)列MQfinal Thread mThread;//Looper關(guān)聯(lián)的當(dāng)前線程private Printer mLogging;/** 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);}/* 我們調(diào)用該方法會(huì)在調(diào)用線程的TLS中創(chuàng)建Looper對(duì)象*/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對(duì)象設(shè)置為當(dāng)前線程的一個(gè)本地變量}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Prepare()之后的的圖:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
2)Looper.loop()源碼
/*** Run the message queue in this thread. Be sure to call* {@link #quit()} to end the loop.*在當(dāng)前線程中執(zhí)行消息隊(duì)列,確定調(diào)用quit()結(jié)束循環(huán)*/public static void loop() {final Looper me = myLooper();//獲得Looper對(duì)象if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}final MessageQueue queue = me.mQueue;//獲得Loop對(duì)象關(guān)聯(lián)的消息隊(duì)列/*沒看懂,不影響理解*/ // 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();/*死循環(huán)處理消息隊(duì)列*/for (;;) {Message msg = queue.next(); // might block,從消息隊(duì)列中獲取消息Messageif (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 loggerPrinter logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}/*這一句非常重要,將真正的處理工作交給message的target,即后面要講的handler*/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(); // 回收message資源}}/*** Return the Looper object associated with the current thread. Returns* null if the calling thread is not associated with a Looper.*返回與當(dāng)前線程相關(guān)聯(lián)的Looper對(duì)象*/public static Looper myLooper() {return sThreadLocal.get();//其實(shí)就是從線程的本地變量里面取值}/*** Return the {@link MessageQueue} object associated with the current* thread. This must be called from a thread running a Looper, or a* NullPointerException will be thrown.* 返回與當(dāng)前線程相關(guān)聯(lián)的MessageQueue對(duì)象*/public static MessageQueue myQueue() {return myLooper().mQueue;}/*初始化Looper的兩個(gè)屬性,關(guān)聯(lián)的線程和消息隊(duì)列*/private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();} 調(diào)用loop方法后,Looper線程就開始真正工作了,它不斷從自己的MQ中取出隊(duì)頭的消息(也叫任務(wù))執(zhí)行
? ? ? ? ? ? ? ? ? ?
Looper有了基本的了解,總結(jié)幾點(diǎn):
1.每個(gè)線程有且最多只能有一個(gè)Looper對(duì)象,它是一個(gè)ThreadLocal就是Looper對(duì)象
2.Looper內(nèi)部有一個(gè)消息隊(duì)列,loop()方法調(diào)用后線程開始不斷從隊(duì)列中取出消息執(zhí)行
3.Looper使一個(gè)線程變成Looper線程。
那么,我們?nèi)绾瓮鵐Q上添加消息呢?下面有請(qǐng)Handler
Handler分析:
handler扮演了往MQ上添加消息和處理消息的角色(只處理由自己發(fā)出的消息),即通知MQ它要執(zhí)行一個(gè)任務(wù)(sendMessage),并在loop到自己的時(shí)候執(zhí)行該任務(wù)(handleMessage),整個(gè)過(guò)程是異步的。handler創(chuàng)建時(shí)會(huì)關(guān)聯(lián)一個(gè)looper,默認(rèn)的構(gòu)造方法將關(guān)聯(lián)當(dāng)前線程的looper,不過(guò)這也是可以set的
為之前的LooperThread類加入Handler:
public class LooperThread extends Thread {private Handler handler1;private Handler handler2;@Overridepublic void run() {// 將當(dāng)前線程初始化為L(zhǎng)ooper線程Looper.prepare();// 實(shí)例化兩個(gè)handlerhandler1 = new Handler();// 開始循環(huán)處理消息隊(duì)列Looper.loop();} } 加入handler后的效果:
1,Handler發(fā)送消息
可以使用
post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long)和 sendMessageDelayed(Message, long)這些方法向MQ上發(fā)送消息了。光看這些API你可能會(huì)覺得handler能發(fā)兩種消息,一種是Runnable對(duì)象,一種是message對(duì)象,這是直觀的理解,但其實(shí)post發(fā)出的Runnable對(duì)象最后都被封裝成message對(duì)象
/*** Causes the Runnable r to be added to the message queue.* The runnable will be run on the thread to which this handler is * attached. * * @param r The Runnable that will be executed.* * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting.*//*把一個(gè)Runnable對(duì)象加入消息隊(duì)列,任務(wù)將在當(dāng)前Handler綁定的線程中執(zhí)行,說(shuō)白了就是當(dāng)前線程執(zhí)行任務(wù)*/public final boolean post(Runnable r){return sendMessageDelayed(getPostMessage(r), 0);}/*** Causes the Runnable r to be added to the message queue, to be run* at a specific time given by <var>uptimeMillis</var>.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.* The runnable will be run on the thread to which this handler is attached.** @param r The Runnable that will be executed.* @param uptimeMillis The absolute time at which the callback should run,* using the {@link android.os.SystemClock#uptimeMillis} time-base.* * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting. Note that a* result of true does not mean the Runnable will be processed -- if* the looper is quit before the delivery time of the message* occurs then the message will be dropped.*/public final boolean postAtTime(Runnable r, long uptimeMillis){return sendMessageAtTime(getPostMessage(r), uptimeMillis);}/*** Causes the Runnable r to be added to the message queue, to be run* at a specific time given by <var>uptimeMillis</var>.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.* The runnable will be run on the thread to which this handler is attached.** @param r The Runnable that will be executed.* @param uptimeMillis The absolute time at which the callback should run,* using the {@link android.os.SystemClock#uptimeMillis} time-base.* * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting. Note that a* result of true does not mean the Runnable will be processed -- if* the looper is quit before the delivery time of the message* occurs then the message will be dropped.* * @see android.os.SystemClock#uptimeMillis*/public final boolean postAtTime(Runnable r, Object token, long uptimeMillis){return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);}/*** Causes the Runnable r to be added to the message queue, to be run* after the specified amount of time elapses.* The runnable will be run on the thread to which this handler* is attached.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.* * @param r The Runnable that will be executed.* @param delayMillis The delay (in milliseconds) until the Runnable* will be executed.* * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting. Note that a* result of true does not mean the Runnable will be processed --* if the looper is quit before the delivery time of the message* occurs then the message will be dropped.*/public final boolean postDelayed(Runnable r, long delayMillis){return sendMessageDelayed(getPostMessage(r), delayMillis);}/*** Posts a message to an object that implements Runnable.* Causes the Runnable r to executed on the next iteration through the* message queue. The runnable will be run on the thread to which this* handler is attached.* <b>This method is only for use in very special circumstances -- it* can easily starve the message queue, cause ordering problems, or have* other unexpected side-effects.</b>* * @param r The Runnable that will be executed.* * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting.*/public final boolean postAtFrontOfQueue(Runnable r){return sendMessageAtFrontOfQueue(getPostMessage(r));}/*** Pushes a message onto the end of the message queue after all pending messages* before the current time. It will be received in {@link #handleMessage},* in the thread attached to this handler.* * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting.*//*把一個(gè)消息放入消息隊(duì)列中,返回true*/public final boolean sendMessage(Message msg){return sendMessageDelayed(msg, 0);}/*** Sends a Message containing only the what value.* * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting.*//*把一個(gè)只有what的消息放入到消息隊(duì)列中*/public final boolean sendEmptyMessage(int what){return sendEmptyMessageDelayed(what, 0);}/*** Sends a Message containing only the what value, to be delivered* after the specified amount of time elapses.* @see #sendMessageDelayed(android.os.Message, long) * * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting.*/public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {Message msg = Message.obtain();msg.what = what;return sendMessageDelayed(msg, delayMillis);}/*** Sends a Message containing only the what value, to be delivered * at a specific time.* @see #sendMessageAtTime(android.os.Message, long)* * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting.*/public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {Message msg = Message.obtain();msg.what = what;return sendMessageAtTime(msg, uptimeMillis);}/*** Enqueue a message into the message queue after all pending messages* before (current time + delayMillis). You will receive it in* {@link #handleMessage}, in the thread attached to this handler.* * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the* looper processing the message queue is exiting. Note that a* result of true does not mean the message will be processed -- if* the looper is quit before the delivery time of the message* occurs then the message will be dropped.*/public final boolean sendMessageDelayed(Message msg, long delayMillis){if (delayMillis < 0) {delayMillis = 0;}return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);} Handler處理消息:
/*** Subclasses must implement this to receive messages.*子類必須實(shí)現(xiàn)這個(gè)方法接收消息*/public void handleMessage(Message msg) {}/*** Handle system messages here.*處理系統(tǒng)的消息, 處理消息,該方法由looper調(diào)用 msg.target.dispatchMessage(msg);就是把消息交給Handler來(lái)處理*/public void dispatchMessage(Message msg) {if (msg.callback != null) {// 如果message設(shè)置了callback,即runnable消息,處理callback!handleCallback(msg);} else {// 如果handler本身設(shè)置了callback,則執(zhí)行callbackif (mCallback != null) {/* 這種方法允許讓activity等來(lái)實(shí)現(xiàn)Handler.Callback接口,避免了自己編寫handler重寫handleMessage方法*/if (mCallback.handleMessage(msg)) {return;}}// 如果message沒有callback,則調(diào)用handler的鉤子方法handleMessagehandleMessage(msg);}}
相關(guān)理論看之前的文章http://blog.csdn.net/tuke_tuke/article/details/50783153
總結(jié)
以上是生活随笔為你收集整理的Android的Handler,Looper源码剖析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android的Crash崩溃解决方案-
- 下一篇: 【错误记录】-eclipse 导入类 提