編輯:Android 開發實例
Message:消息,其中包含了消息ID,消息處理對象以及處理的數據等,由MessageQueue統一列隊,終由Handler處理。 Handler:處理者,負責Message的發送及處理。使用Handler時,需要實現handleMessage(Message msg)方法來對特定的Message進行處理,例如更新UI等。 MessageQueue:消息隊列,用來存放Handler發送過來的消息,並按照FIFO規則執行。當然,存放Message並非實際意義的保存,而是將Message以鏈表的方式串聯起來的,等待Looper的抽取。 Looper:消息泵,不斷地從MessageQueue中抽取Message執行。因此,一個MessageQueue需要一個Looper。 Thread:線程,負責調度整個消息循環,即消息循環的執行場所。
Android 系統的消息隊列和消息循環都是針對具體執行緒的,一個執行緒可以存在(當然也可以不存在)一個消息隊列和一個消息循環(Looper),特定執行緒的消息只能分發給本執行緒,不能進行跨執行緒、跨行程通訊。但是創建的工作執行緒預設是沒有消息循環和消息隊列的,如果想讓該執行緒具有消息隊列和消息循環,需要在執行緒中首先呼叫 Looper.prepare() 來創建消息隊列,然後呼叫 Looper.loop() 進入消息循環。如下例所示:
LooperThread Thread { Handler mHandler; run() { Looper.prepare(); mHandler = Handler() { handleMessage(Message msg) { } }; Looper.loop(); } }
//Looper 類別分析
//沒找到合適的分析程式碼的辦法,只能這麼來了。每個重要行的上面都會加上註釋
//功能方面的程式碼會在程式碼前加上一段分析
public class Looper { //static變量,判斷是否打印調試信息。 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(). //線程本地存儲功能的封裝,TLS,thread local storage,什麼意思呢?因為存儲要麼在棧上,例如函數內定義的內部變量。要麼在堆上,例如new或者malloc出來的東西 //但是現在的系統比如Linux和windows都提供了線程本地存儲空間,也就是這個存儲空間是和線程相關的,一個線程內有一個內部存儲空間,這樣的話我把線程相關的東西就存儲到 //這個線程的TLS中,就不用放在堆上而進行同步操作了。 private static final ThreadLocal sThreadLocal = new ThreadLocal(); //消息隊列,MessageQueue,看名字就知道是個queue.. final MessageQueue mQueue; volatile boolean mRun; //和本looper相關的那個線程,初始化為null Thread mThread; private Printer mLogging = null; //static變量,代表一個UI Process(也可能是service吧,這裡默認就是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中設上這個Looper對象的,如果這個線程已經設過了looper的話就會報錯 //這說明,一個線程只能設一個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設置的UI程序的主消息循環,注意,這個主消息循環是不會主動退出的 // public static final void prepareMainLooper() { prepare(); setMainLooper(myLooper()); //判斷主消息循環是否能退出.... //通過quit函數向looper發出退出申請 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. */ //消息循環,整個程序就在這裡while了。 //這個是static函數喔! public static final void loop() { Looper me = myLooper();//從該線程中取出對應的looper對象 MessageQueue queue = me.mQueue;//取消息隊列對象... while (true) { Message msg = queue.next(); // might block取消息隊列中的一個待處理消息.. //if (!me.mRun) {//是否需要退出?mRun是個volatile變量,跨線程同步的,應該是有地方設置它。 // 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. */ //返回和線程相關的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. */ //設置調試輸出對象,looper循環的時候會打印相關信息,用來調試用最好了。 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; } //創建一個新的looper對象, //內部分配一個消息隊列,設置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; } } }
那怎麼往這個消息隊列中發送消息呢?呼叫 looper 的 static 函式 myQueue 可以獲得消息隊列,這樣你就可以自己往裡邊插入消息了。不過這種方法比較麻煩,這個時候 handler 類別就發揮作用了。先來看看 handler 的程式碼,就明白了。
class Handler{ .......... //handler默認構造函數 public Handler() { //這個if是干嘛用的暫時還不明白,涉及到java的深層次的內容了應該 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對象 //如果本線程還沒有設置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搞成一個了 //這樣的話,我通過handler的封裝機制加消息的話,就相當於直接加到了looper的消息隊列中去了 mQueue = mLooper.mQueue; mCallback = null; } //還有好幾種構造函數,一個是帶callback的,一個是帶looper的 //由外部設置looper public Handler(Looper looper) { mLooper = looper; mQueue = looper.mQueue; mCallback = null; } // 帶callback的,一個handler可以設置一個callback。如果有callback的話, //凡是發到通過這個handler發送的消息,都有callback處理,相當於一個總的集中處理 //待會看dispatchMessage的時候再分析 public Handler(Looper looper, Callback callback) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; } // //通過handler發送消息 //調用了內部的一個sendMessageDelayed public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } //FT,又封裝了一層,這回是調用sendMessageAtTime了 //因為延時時間是基於當前調用時間的,所以需要獲得絕對時間傳遞給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設置為自己,然後加入到消息隊列中 //對於隊列這種數據結構來說,操作比較簡單了 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中的那個消息循環處理嗎 //從消息隊列中得到一個消息後,會調用它的target的dispatchMesage函數 //message的target已經設置為handler了,所以 //最後會轉到handler的msg處理上來 //這裡有個處理流程的問題 public void dispatchMessage(Message msg) { //如果msg本身設置了callback,則直接交給這個callback處理了 if (msg.callback != null) { handleCallback(msg); } else { //如果該handler的callback有的話,則交給這個callback處理了---相當於集中處理 if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } //否則交給派生處理,基類默認處理是什麼都不干 handleMessage(msg); } } .......... }
生成
Message msg = mHandler.obtainMessage(); msg.what = what; msg.sendToTarget();
發送
MessageQueue queue = mQueue; if (queue != null) { msg.target = this; sent = queue.enqueueMessage(msg, uptimeMillis); }
在 Handler.java 的 sendMessageAtTime(Message msg, long uptimeMillis) 方法中,我們看到,它找到它所引用的 MessageQueue,然後將 Message 的 target 設定成自己(目的是為了在處理消息環節,Message 能找到正確的 Handler),再將這個 Message 納入到消息隊列中。
抽取
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() 函式裡,我們看到,這裡有一個死循環,不斷地從 MessageQueue 中獲取下一個(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) 方法裡,其中的一個分支就是呼叫 handleMessage 方法來處理這條 Message,而這也正是我們在職責處描述使用 Handler 時需要實現 handleMessage(Message msg) 的原因。
至於 dispatchMessage 方法中的另外一個分支,我將會在後面的內容中說明。
至此,我們看到,一個 Message 經由 Handler 的發送、MessageQueue 的入隊、Looper 的抽取,又再一次地回到 Handler 的懷抱。而繞的這一圈,也正好幫助我們將同步操作變成了異步操作。
3)剩下的部分,我們將討論一下 Handler 所處的執行緒及更新 UI 的方式。
在主執行緒(UI 執行緒)裡,如果創建 Handler 時不傳入 Looper 對象,那麼將直接使用主執行緒(UI 執行緒)的 Looper 對象(系統已經幫我們創建了);在其它執行緒裡,如果創建 Handler 時不傳入 Looper 對象,那麼這個 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(); } }
在創建 Handler 之前,為該執行緒準備好一個 Looper(Looper.prepare),然後讓這個 Looper 跑起來(Looper.loop),抽取 Message,這樣 Handler 才能正常工作。
因此,Handler 處理消息總是在創建 Handler 的執行緒裡運行。而我們的消息處理中,不乏更新 UI 的操作,不正確的執行緒直接更新 UI 將引發異常。因此,需要時刻關心 Handler 在哪個執行緒裡創建的。
如何更新 UI 才能不出異常呢?SDK 告訴我們,有以下 4 種方式可以從其它執行緒存取 UI 執行緒:
· Activity.runOnUiThread(Runnable)
· View.post(Runnable)
· View.postDelayed(Runnable, long)
· Handler
其中,重點說一下的是 View.post(Runnable) 方法。在 post(Runnable action) 方法裡,View 獲得當前執行緒(即 UI 執行緒)的 Handler,然後將 action 對象 post 到 Handler 裡。在 Handler 裡,它將傳遞過來的 action 對象包裝成一個 Message(Message 的 callback 為 action),然後將其投入 UI 執行緒的消息循環中。在 Handler 再次處理該 Message 時,有一條分支(未解釋的那條)就是為它所設,直接呼叫 runnable 的 run 方法。而此時,已經路由到 UI 執行緒裡,因此,我們可以毫無顧慮地來更新 UI。
4)幾點小結
· Handler 的處理過程運行在創建 Handler 的執行緒裡
· 一個 Looper 對應一個 MessageQueue
· 一個執行緒對應一個 Looper
· 一個 Looper 可以對應多個 Handler
· 不確定當前執行緒時,更新 UI 時盡量呼叫 post 方法
Android MediaPlayer 教學:打造可快轉的音樂播放器
要在 Android 上播放音訊或影片,最直接的方式就是使用 MediaPlayer 類別。它是內建媒體播放服務的入口,音訊、影片與串流格式都能 handle。 取得 M
Android 本地化入門:用 values-語系 資料夾做好多國語言支援
一支 App 上線後,使用者可能來自任何國家。若畫面上永遠只有一種語言,對不熟悉該語言的人來說形同不可用。本地化要解決的就是這個問題:讓 App 依裝置的語言環境,自動呈
Android ApiDemo 系列十:QuickContactsDemo 與 Content Provider
在 Android 的 ApiDemo 中,QuickContactsDemo 常用來示範如何透過 Content Provider 存取系統聯絡人資料。Content
Android 應用程式簽名步驟與相關知識
Android 要求每個應用程式都必須經過數字簽名才能安裝。簽名的作用不是決定使用者可以安裝哪些應用程式,而是用來標識作者並在應用程式之間建立信任關係。為什麼需要簽名開發