日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android的Handler,Looper源码剖析

發布時間:2025/3/20 Android 55 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android的Handler,Looper源码剖析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

之前了解android的消息處理機制,但是源碼看的少,現在把Looper,Handler,Message這幾個類的源碼分析一哈

android的消息處理有三個核心類:Looper,Handler和Message。其實還有一個Message Queue(消息隊列),但是MQ被封裝到Looper里面了,我們不會直接與MQ打交道,因此我沒將其作為核心類

Looper源碼:

Looper的字面意思是“循環者”,它被設計用來使一個普通線程變成Looper線程。所謂Looper線程就是循環工作的線程

使用Looper類創建Looper線程Demo:

public class LooperThread extends Thread {@Overridepublic void run() {// 將當前線程初始化為Looper線程Looper.prepare();// ...其他處理,如實例化handler// 開始循環處理消息隊列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()./*如果沒有調用prepare將Looper對象設置為線程的本地變量,則sThreadLocal.get()為空*//*// 每個線程中的Looper對象其實是一個ThreadLocal,即線程本地存儲(TLS)對象*/static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//當前線程的本地變量private static Looper sMainLooper; // guarded by Looper.classfinal MessageQueue mQueue;//Looper維護的消息隊列MQfinal Thread mThread;//Looper關聯的當前線程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);}/* 我們調用該方法會在調用線程的TLS中創建Looper對象*/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對象設置為當前線程的一個本地變量}

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Prepare()之后的的圖:

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

現在你的線程中有一個Looper對象,它的內部維護了一個消息隊列MQ。注意,一個Thread只能有一個Looper對象
2)Looper.loop()源碼

/*** Run the message queue in this thread. Be sure to call* {@link #quit()} to end the loop.*在當前線程中執行消息隊列,確定調用quit()結束循環*/public static void loop() {final Looper me = myLooper();//獲得Looper對象if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}final MessageQueue queue = me.mQueue;//獲得Loop對象關聯的消息隊列/*沒看懂,不影響理解*/ // 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,從消息隊列中獲取消息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.*返回與當前線程相關聯的Looper對象*/public static Looper myLooper() {return sThreadLocal.get();//其實就是從線程的本地變量里面取值}/*** 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.* 返回與當前線程相關聯的MessageQueue對象*/public static MessageQueue myQueue() {return myLooper().mQueue;}/*初始化Looper的兩個屬性,關聯的線程和消息隊列*/private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();} 調用loop方法后,Looper線程就開始真正工作了,它不斷從自己的MQ中取出隊頭的消息(也叫任務)執行

? ? ? ? ? ? ? ? ? ?
Looper有了基本的了解,總結幾點:
1.每個線程有且最多只能有一個Looper對象,它是一個ThreadLocal就是Looper對象
2.Looper內部有一個消息隊列,loop()方法調用后線程開始不斷從隊列中取出消息執行
3.Looper使一個線程變成Looper線程

那么,我們如何往MQ上添加消息呢?下面有請Handler

Handler分析:

handler扮演了往MQ上添加消息和處理消息的角色(只處理由自己發出的消息),即通知MQ它要執行一個任務(sendMessage),并在loop到自己的時候執行該任務(handleMessage),整個過程是異步的。handler創建時會關聯一個looper,默認的構造方法將關聯當前線程的looper,不過這也是可以set的

為之前的LooperThread類加入Handler:

public class LooperThread extends Thread {private Handler handler1;private Handler handler2;@Overridepublic void run() {// 將當前線程初始化為Looper線程Looper.prepare();// 實例化兩個handlerhandler1 = new Handler();// 開始循環處理消息隊列Looper.loop();} } 加入handler后的效果:



1,Handler發送消息

可以使用

post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long)和 sendMessageDelayed(Message, long)這些方法向MQ上發送消息了。光看這些API你可能會覺得handler能發兩種消息,一種是Runnable對象,一種是message對象,這是直觀的理解,但其實post發出的Runnable對象最后都被封裝成message對象

/*** 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.*//*把一個Runnable對象加入消息隊列,任務將在當前Handler綁定的線程中執行,說白了就是當前線程執行任務*/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.*//*把一個消息放入消息隊列中,返回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.*//*把一個只有what的消息放入到消息隊列中*/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.*子類必須實現這個方法接收消息*/public void handleMessage(Message msg) {}/*** Handle system messages here.*處理系統的消息, 處理消息,該方法由looper調用 msg.target.dispatchMessage(msg);就是把消息交給Handler來處理*/public void dispatchMessage(Message msg) {if (msg.callback != null) {// 如果message設置了callback,即runnable消息,處理callback!handleCallback(msg);} else {// 如果handler本身設置了callback,則執行callbackif (mCallback != null) {/* 這種方法允許讓activity等來實現Handler.Callback接口,避免了自己編寫handler重寫handleMessage方法*/if (mCallback.handleMessage(msg)) {return;}}// 如果message沒有callback,則調用handler的鉤子方法handleMessagehandleMessage(msg);}}
相關理論看之前的文章http://blog.csdn.net/tuke_tuke/article/details/50783153


總結

以上是生活随笔為你收集整理的Android的Handler,Looper源码剖析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。