Android消息處理機(jī)制Looper和Handler詳解
Message:消息,其中包含了消息ID,消息處理對象以及處理的數(shù)據(jù)等,由MessageQueue統(tǒng)一列隊(duì),終由Handler處理。 Handler:處理者,負(fù)責(zé)Message的發(fā)送及處理。使用Handler時(shí),需要實(shí)現(xiàn)handleMessage(Message msg)方法來對特定的Message進(jìn)行處理,例如更新UI等。 MessageQueue:消息隊(duì)列,用來存放Handler發(fā)送過來的消息,并按照FIFO規(guī)則執(zhí)行。當(dāng)然,存放Message并非實(shí)際意義的保存,而是將Message以鏈表的方式串聯(lián)起來的,等待Looper的抽取。 Looper:消息泵,不斷地從MessageQueue中抽取Message執(zhí)行。因此,一個(gè)MessageQueue需要一個(gè)Looper。 Thread:線程,負(fù)責(zé)調(diào)度整個(gè)消息循環(huán),即消息循環(huán)的執(zhí)行場所。
Android系統(tǒng)的消息隊(duì)列和消息循環(huán)都是針對具體線程的,一個(gè)線程可以存在(當(dāng)然也可以不存在)一個(gè)消息隊(duì)列和一個(gè)消 息循環(huán)(Looper),特定線程的消息只能分發(fā)給本線程,不能進(jìn)行跨線程,跨進(jìn)程通訊。但是創(chuàng)建的工作線程默認(rèn)是沒有消息循環(huán)和消息隊(duì)列的,如果想讓該 線程具有消息隊(duì)列和消息循環(huán),需要在線程中首先調(diào)用Looper.prepare()來創(chuàng)建消息隊(duì)列,然后調(diào)用Looper.loop()進(jìn)入消息循環(huán)。 如下例所示:
LooperThread Thread { Handler mHandler; run() { Looper.prepare(); mHandler = Handler() { handleMessage(Message msg) { } }; Looper.loop(); } }
//Looper類分析
//沒找到合適的分析代碼的辦法,只能這么來了。每個(gè)重要行的上面都會(huì)加上注釋
//功能方面的代碼會(huì)在代碼前加上一段分析
public class Looper { //static變量,判斷是否打印調(diào)試信息。 private static final boolean DEBUG = false; private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; // sThreadLocal.get() will return null unless you've called prepare(). //線程本地存儲(chǔ)功能的封裝,TLS,thread local storage,什么意思呢?因?yàn)榇鎯?chǔ)要么在棧上,例如函數(shù)內(nèi)定義的內(nèi)部變量。要么在堆上,例如new或者malloc出來的東西 //但是現(xiàn)在的系統(tǒng)比如Linux和windows都提供了線程本地存儲(chǔ)空間,也就是這個(gè)存儲(chǔ)空間是和線程相關(guān)的,一個(gè)線程內(nèi)有一個(gè)內(nèi)部存儲(chǔ)空間,這樣的話我把線程相關(guān)的東西就存儲(chǔ)到 //這個(gè)線程的TLS中,就不用放在堆上而進(jìn)行同步操作了。 private static final ThreadLocal sThreadLocal = new ThreadLocal(); //消息隊(duì)列,MessageQueue,看名字就知道是個(gè)queue.. final MessageQueue mQueue; volatile boolean mRun; //和本looper相關(guān)的那個(gè)線程,初始化為null Thread mThread; private Printer mLogging = null; //static變量,代表一個(gè)UI Process(也可能是service吧,這里默認(rèn)就是UI)的主線程 private static Looper mMainLooper = null; /** 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()}. */ //往TLS中設(shè)上這個(gè)Looper對象的,如果這個(gè)線程已經(jīng)設(shè)過了looper的話就會(huì)報(bào)錯(cuò) //這說明,一個(gè)線程只能設(shè)一個(gè)looper public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper()); } /** 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. * {@link #prepare()} */ //由framework設(shè)置的UI程序的主消息循環(huán),注意,這個(gè)主消息循環(huán)是不會(huì)主動(dòng)退出的 // public static final void prepareMainLooper() { prepare(); setMainLooper(myLooper()); //判斷主消息循環(huán)是否能退出.... //通過quit函數(shù)向looper發(fā)出退出申請 if (Process.supportsProcesses()) { myLooper().mQueue.mQuitAllowed = false; } } private synchronized static void setMainLooper(Looper looper) { mMainLooper = looper; } /** Returns the application's main looper, which lives in the main thread of the application. */ public synchronized static final Looper getMainLooper() { return mMainLooper; } /** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */ //消息循環(huán),整個(gè)程序就在這里while了。 //這個(gè)是static函數(shù)喔! public static final void loop() { Looper me = myLooper();//從該線程中取出對應(yīng)的looper對象 MessageQueue queue = me.mQueue;//取消息隊(duì)列對象... while (true) { Message msg = queue.next(); // might block取消息隊(duì)列中的一個(gè)待處理消息.. //if (!me.mRun) {//是否需要退出?mRun是個(gè)volatile變量,跨線程同步的,應(yīng)該是有地方設(shè)置它。 // break; //} if (msg != null) { if (msg.target == null) { // No target is a magic identifier for the quit message. return; } if (me.mLogging!= null) me.mLogging.println( ">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what ); msg.target.dispatchMessage(msg); if (me.mLogging!= null) me.mLogging.println( "<<<<< Finished to " + msg.target + " " + msg.callback); msg.recycle(); } } } /** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ //返回和線程相關(guān)的looper public static final Looper myLooper() { return (Looper)sThreadLocal.get(); } /** * Control logging of messages as they are processed by this Looper. If * enabled, a log message will be written to <var>printer</var> * at the beginning and ending of each message dispatch, identifying the * target Handler and message contents. * * @param printer A Printer object that will receive log messages, or * null to disable message logging. */ //設(shè)置調(diào)試輸出對象,looper循環(huán)的時(shí)候會(huì)打印相關(guān)信息,用來調(diào)試用最好了。 public void setMessageLogging(Printer printer) { mLogging = printer; } /** * 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. */ public static final MessageQueue myQueue() { return myLooper().mQueue; } //創(chuàng)建一個(gè)新的looper對象, //內(nèi)部分配一個(gè)消息隊(duì)列,設(shè)置mRun為true private Looper() { mQueue = new MessageQueue(); mRun = true; mThread = Thread.currentThread(); } public void quit() { Message msg = Message.obtain(); // NOTE: By enqueueing directly into the message queue, the // message is left with a null target. This is how we know it is // a quit message. mQueue.enqueueMessage(msg, 0); } /** * Return the Thread associated with this Looper. */ public Thread getThread() { return mThread; } //后面就簡單了,打印,異常定義等。 public void dump(Printer pw, String prefix) { pw.println(prefix + this); pw.println(prefix + "mRun=" + mRun); pw.println(prefix + "mThread=" + mThread); pw.println(prefix + "mQueue=" + ((mQueue != null) ? mQueue : "(null")); if (mQueue != null) { synchronized (mQueue) { Message msg = mQueue.mMessages; int n = 0; while (msg != null) { pw.println(prefix + " Message " + n + ": " + msg); n++; msg = msg.next; } pw.println(prefix + "(Total messages: " + n + ")"); } } } public String toString() { return "Looper{" + Integer.toHexString(System.identityHashCode(this)) + "}"; } static class HandlerException extends Exception { HandlerException(Message message, Throwable cause) { super(createMessage(cause), cause); } static String createMessage(Throwable cause) { String causeMsg = cause.getMessage(); if (causeMsg == null) { causeMsg = cause.toString(); } return causeMsg; } } }
那怎么往這個(gè)消息隊(duì)列中發(fā)送消息呢??調(diào)用looper的static函數(shù)myQueue可以獲得消息隊(duì)列,這樣你就可用自己往里邊插入消息了。不過這種方法比較麻煩,這個(gè)時(shí)候handler類就發(fā)揮作用了。先來看看handler的代碼,就明白了。
class Handler{ .......... //handler默認(rèn)構(gòu)造函數(shù) public Handler() { //這個(gè)if是干嘛用的暫時(shí)還不明白,涉及到j(luò)ava的深層次的內(nèi)容了應(yīng)該 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()); } } //獲取本線程的looper對象 //如果本線程還沒有設(shè)置looper,這回拋異常 mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } //無恥啊,直接把looper的queue和自己的queue搞成一個(gè)了 //這樣的話,我通過handler的封裝機(jī)制加消息的話,就相當(dāng)于直接加到了looper的消息隊(duì)列中去了 mQueue = mLooper.mQueue; mCallback = null; } //還有好幾種構(gòu)造函數(shù),一個(gè)是帶callback的,一個(gè)是帶looper的 //由外部設(shè)置looper public Handler(Looper looper) { mLooper = looper; mQueue = looper.mQueue; mCallback = null; } // 帶callback的,一個(gè)handler可以設(shè)置一個(gè)callback。如果有callback的話, //凡是發(fā)到通過這個(gè)handler發(fā)送的消息,都有callback處理,相當(dāng)于一個(gè)總的集中處理 //待會(huì)看dispatchMessage的時(shí)候再分析 public Handler(Looper looper, Callback callback) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; } // //通過handler發(fā)送消息 //調(diào)用了內(nèi)部的一個(gè)sendMessageDelayed public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } //FT,又封裝了一層,這回是調(diào)用sendMessageAtTime了 //因?yàn)檠訒r(shí)時(shí)間是基于當(dāng)前調(diào)用時(shí)間的,所以需要獲得絕對時(shí)間傳遞給sendMessageAtTime 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) { boolean sent = false; MessageQueue queue = mQueue; if (queue != null) { //把消息的target設(shè)置為自己,然后加入到消息隊(duì)列中 //對于隊(duì)列這種數(shù)據(jù)結(jié)構(gòu)來說,操作比較簡單了 msg.target = this; sent = queue.enqueueMessage(msg, uptimeMillis); } else { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); } return sent; } //還記得looper中的那個(gè)消息循環(huán)處理嗎 //從消息隊(duì)列中得到一個(gè)消息后,會(huì)調(diào)用它的target的dispatchMesage函數(shù) //message的target已經(jīng)設(shè)置為handler了,所以 //最后會(huì)轉(zhuǎn)到handler的msg處理上來 //這里有個(gè)處理流程的問題 public void dispatchMessage(Message msg) { //如果msg本身設(shè)置了callback,則直接交給這個(gè)callback處理了 if (msg.callback != null) { handleCallback(msg); } else { //如果該handler的callback有的話,則交給這個(gè)callback處理了---相當(dāng)于集中處理 if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } //否則交給派生處理,基類默認(rèn)處理是什么都不干 handleMessage(msg); } } .......... }
生成
Message msg = mHandler.obtainMessage(); msg.what = what; msg.sendToTarget();
發(fā)送
MessageQueue queue = mQueue; if (queue != null) { msg.target = this; sent = queue.enqueueMessage(msg, uptimeMillis); }
在Handler.java的sendMessageAtTime(Message msg, long uptimeMillis)方法中,我們看到,它找到它所引用的MessageQueue,然后將Message的target設(shè)定成自己(目的是為了在處理消息環(huán)節(jié),Message能找到正確的Handler),再將這個(gè)Message納入到消息隊(duì)列中。
抽取
Looper me = myLooper(); MessageQueue queue = me.mQueue; while (true) { Message msg = queue.next(); // might block if (msg != null) { if (msg.target == null) { // No target is a magic identifier for the quit message. return; } msg.target.dispatchMessage(msg); msg.recycle(); } }
在Looper.java的loop()函數(shù)里,我們看到,這里有一個(gè)死循環(huán),不斷地從MessageQueue中獲取下一個(gè)(next方法)Message,然后通過Message中攜帶的target信息,交由正確的Handler處理(dispatchMessage方法)。
處理
if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); }
在Handler.java的dispatchMessage(Message msg)方法里,其中的一個(gè)分支就是調(diào)用handleMessage方法來處理這條Message,而這也正是我們在職責(zé)處描述使用Handler時(shí)需要實(shí)現(xiàn)handleMessage(Message msg)的原因。
至于dispatchMessage方法中的另外一個(gè)分支,我將會(huì)在后面的內(nèi)容中說明。
至此,我們看到,一個(gè)Message經(jīng)由Handler的發(fā)送,MessageQueue的入隊(duì),Looper的抽取,又再一次地回到Handler的懷抱。而繞的這一圈,也正好幫助我們將同步操作變成了異步操作。
3)剩下的部分,我們將討論一下Handler所處的線程及更新UI的方式。
在主線程(UI線程)里,如果創(chuàng)建Handler時(shí)不傳入Looper對象,那么將直接使用主線程(UI線程)的Looper對象(系統(tǒng)已經(jīng)幫我們創(chuàng)建了);在其它線程里,如果創(chuàng)建Handler時(shí)不傳入Looper對象,那么,這個(gè)Handler將不能接收處理消息。在這種情況下,通用的作法是:
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
在創(chuàng)建Handler之前,為該線程準(zhǔn)備好一個(gè)Looper(Looper.prepare),然后讓這個(gè)Looper跑起來(Looper.loop),抽取Message,這樣,Handler才能正常工作。
因此,Handler處理消息總是在創(chuàng)建Handler的線程里運(yùn)行。而我們的消息處理中,不乏更新UI的操作,不正確的線程直接更新UI將引發(fā)異常。因此,需要時(shí)刻關(guān)心Handler在哪個(gè)線程里創(chuàng)建的。
如何更新UI才能不出異常呢?SDK告訴我們,有以下4種方式可以從其它線程訪問UI線程:
· Activity.runOnUiThread(Runnable)
· View.post(Runnable)
· View.postDelayed(Runnable, long)
· Handler
其中,重點(diǎn)說一下的是View.post(Runnable)方法。在post(Runnable action)方法里,View獲得當(dāng)前線程(即UI線程)的Handler,然后將action對象post到Handler里。在Handler里,它將傳遞過來的action對象包裝成一個(gè)Message(Message的callback為action),然后將其投入U(xiǎn)I線程的消息循環(huán)中。在Handler再次處理該Message時(shí),有一條分支(未解釋的那條)就是為它所設(shè),直接調(diào)用runnable的run方法。而此時(shí),已經(jīng)路由到UI線程里,因此,我們可以毫無顧慮的來更新UI。
4) 幾點(diǎn)小結(jié)
· Handler的處理過程運(yùn)行在創(chuàng)建Handler的線程里
· 一個(gè)Looper對應(yīng)一個(gè)MessageQueue
· 一個(gè)線程對應(yīng)一個(gè)Looper
· 一個(gè)Looper可以對應(yīng)多個(gè)Handler
· 不確定當(dāng)前線程時(shí),更新UI時(shí)盡量調(diào)用post方法
相關(guān)文章
Android中利用matrix 控制圖片的旋轉(zhuǎn)、縮放、移動(dòng)
本篇文章是對Android中利用matrix 控制圖片的旋轉(zhuǎn)、縮放、移動(dòng)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06Android利用ViewPager實(shí)現(xiàn)用戶引導(dǎo)界面效果的方法
這篇文章主要介紹了Android利用ViewPager實(shí)現(xiàn)用戶引導(dǎo)界面效果的方法,結(jié)合實(shí)例形式詳細(xì)分析了Android軟件功能界面的初始化、view實(shí)例化、動(dòng)畫功能實(shí)現(xiàn)與布局相關(guān)技巧,需要的朋友可以參考下2016-07-07android配合viewpager實(shí)現(xiàn)可滑動(dòng)的標(biāo)簽欄示例分享
本文主要介紹了android實(shí)現(xiàn)可滑動(dòng)的標(biāo)簽欄示例,配合viewpager作為標(biāo)簽欄,且可以設(shè)置每頁顯示的標(biāo)簽個(gè)數(shù),超出可滑動(dòng)顯示,需要的朋友可以參考下2014-02-02Android基礎(chǔ)之使用Fragment控制切換多個(gè)頁面
Android官方已經(jīng)提供了Fragment的各種使用的Demo例子,在我們SDK下面的API Demo里面就包含了Fragment的各種使用例子,需要看Demo的朋友,直接看API Demo那個(gè)程序就可以了,不用到處去找。里面分開不同功能,實(shí)現(xiàn)了不同的類2013-07-07關(guān)于Android實(shí)現(xiàn)簡單的微信朋友圈分享功能
這篇文章主要介紹了關(guān)于Android實(shí)現(xiàn)簡單的微信朋友圈分享功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下2017-02-02