Android線程的Looper敦锌,Handler相關(guān)知識(shí)
Android中的Looper
類馒疹,是用來封裝消息循環(huán)和消息隊(duì)列的一個(gè)類,用于在android線程中進(jìn)行消息處理乙墙。Handler
其實(shí)可以看做是一個(gè)工具類颖变,用來向消息隊(duì)列中插入消息的生均。
Android官方文檔中Looper的介紹: Class used to run a message loop for a thread. Threads by
default do not have a message loop associated with them; to create one, call prepare() in
the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
This is a typical example of the implementation of a Looper thread, using the separation
of prepare() and loop() to create an initial Handler to communicate with the Looper.
Looper實(shí)現(xiàn)原理
1. Looper可以理解為一個(gè)類似輪詢器
2. Looper在創(chuàng)建的時(shí)候,會(huì)自動(dòng)創(chuàng)建一個(gè)MessageQueue(消息隊(duì)列)腥刹。
3. 將內(nèi)部線程對(duì)象指向自動(dòng)創(chuàng)建的線程马胧。
4. 然后當(dāng)Looper開啟的時(shí)候,去不斷遍歷“詢問”消息隊(duì)列衔峰,如果沒有消息佩脊,隊(duì)列為空,那么就繼續(xù)輪詢
垫卤。如果有消息進(jìn)入隊(duì)列威彰,則對(duì)消息進(jìn)行處理,回調(diào)handler的handlemessage方法進(jìn)行處理
Looper創(chuàng)建的流程
Looper類用來為一個(gè)線程開啟一個(gè)消息循環(huán)穴肘。 默認(rèn)情況下android中新誕生的線程是沒有開啟消息循環(huán)的歇盼。(主線程除外,主線程系統(tǒng)會(huì)自動(dòng)為其創(chuàng)建Looper對(duì)象评抚,開啟消息循環(huán)豹缀。) Looper對(duì)象通過MessageQueue來存放消息和事件。一個(gè)線程只能有一個(gè)Looper盈咳,對(duì)應(yīng)一個(gè)MessageQueue耿眉。
通常是通過Handler對(duì)象來與Looper進(jìn)行交互的。Handler可看做是Looper的一個(gè)接口鱼响,用來向指定的Looper發(fā)送消息及定義處理方法鸣剪。 默認(rèn)情況下Handler會(huì)與其被定義時(shí)所在線程的Looper綁定,比如丈积,Handler在主線程中定義筐骇,那么它是與主線程的Looper綁定。
mainHandler = new Handler()
等價(jià)于new Handler(Looper.myLooper())
.Looper.myLooper()
:獲取當(dāng)前進(jìn)程的looper對(duì)象江滨,類似的Looper.getMainLooper()
用于獲取主線程的Looper對(duì)象铛纬。-
在非主線程中直接new Handler() 會(huì)報(bào)如下的錯(cuò)誤:
E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception E/AndroidRuntime( 6173): Java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因是非主線程中默認(rèn)沒有創(chuàng)建Looper對(duì)象,需要先調(diào)用
Looper.prepare()
啟用Looper唬滑。
Looper.prepare()
相關(guān)代碼:/** * 初始化Looper告唆,調(diào)用loop()方法開始循環(huán),調(diào)用quit()退出 * 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) {//一個(gè)線程只能有一個(gè)Looper throw new RuntimeException("Only one Looper may be created per thread"); } //保存Looper sThreadLocal.set(new Looper(quitAllowed)); } /** * 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()} * 初始化主線程的Looper晶密,不要調(diào)用擒悬。因?yàn)殚_啟主線程的時(shí)候系統(tǒng)已經(jīng)默認(rèn)開啟Looper了再次調(diào)用會(huì)報(bào)異常 */ public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
//構(gòu)造函數(shù) private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed);//創(chuàng)建消息隊(duì)列 mThread = Thread.currentThread();//綁定當(dāng)前線程 }
-
Looper.loop()
讓Looper開始工作,從消息隊(duì)列里取消息稻艰,處理消息懂牧。注意:寫在
Looper.loop()
之后的代碼不會(huì)被執(zhí)行,這個(gè)函數(shù)內(nèi)部應(yīng)該是一個(gè)循環(huán)尊勿,當(dāng)調(diào)用mHandler.getLooper().quit
()后僧凤,loop才會(huì)中止畜侦,其后的代碼才能得以運(yùn)行。
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(); 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. //確保此線程的標(biāo)識(shí)是本地進(jìn)程的標(biāo)識(shí)躯保,并跟蹤該標(biāo)識(shí)標(biāo)識(shí)實(shí)際上是什么.旋膳。 Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); //開始一個(gè)死循環(huán) for (;;) { // 從消息隊(duì)列中獲取新的消息,當(dāng)沒有新消息的時(shí)候會(huì)在queue.next()方法中進(jìn)行循環(huán)遍歷 //直到有新的消息或者調(diào)用Looper.quit() Message msg = queue.next(); if (msg == null) {//如果返回的消息為空就表示已經(jīng)調(diào)用MessageQueue.quit();并且已經(jīng)MessageQueue.dispose() // No message indicates that the message queue is quitting. //Return here if the message loop has already quit and been disposed. return; } //msg.target 是Handler對(duì)象吻氧,這里進(jìn)行消息的分發(fā) msg.target.dispatchMessage(msg); // 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); } //Message對(duì)象回收 msg.recycleUnchecked(); } }
Looper.quit()
源碼/** * Quits the looper.退出(會(huì)有消息沒有處理完畢就退出) * <p> * Causes the {@link #loop} method to terminate without processing any * more messages in the message queue. * </p><p> * Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. * </p><p class="note"> * Using this method may be unsafe because some messages may not be delivered * before the looper terminates. Consider using {@link #quitSafely} instead to ensure * that all pending work is completed in an orderly manner. * </p> * * @see #quitSafely */ public void quit() { mQueue.quit(false); } /** * Quits the looper safely.安全退出(消息處理完畢退出) * <p> * Causes the {@link #loop} method to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * However pending delayed messages with due times in the future will not be * delivered before the loop terminates. * </p><p> * Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. * </p> */ public void quitSafely() { mQueue.quit(true); }
-
基于以上知識(shí)溺忧,可實(shí)現(xiàn)主線程給子線程(非主線程)發(fā)送消息咏连。把下面例子中的mHandler聲明成類成員盯孙,在主線程通過mHandler發(fā)送消息即可。
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; //這里可以做兩個(gè)修改UI的操作 //1祟滴,Toast可在這里顯示 //2振惰,Dialog對(duì)話框可以顯示 //3,Snackbar可在非UI線程中調(diào)用顯示垄懂,不需要Looper.perpare().因?yàn)樗腍ander調(diào)用的主線程Looper Looper.loop(); //在調(diào)用looper.quit()之前是不會(huì)被調(diào)用的 } }