Android 官網對Looper對象的說明:
public class Looperextends Object
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.
在訊息處理機制中,訊息都是存放在一個訊息佇列中去,而應用程式的主線程就是圍繞這個訊息佇列進入一個無限迴圈的,直到應用程式退出。如果隊列中有訊息,應用程式的主線程就會把它取出來,並分發給相應的Handler進行處理;如果隊列中沒有訊息,應用程式的主線程就會進入空閑等待狀態,等待下一個訊息的到來。在Android應用程式中,這個訊息迴圈過程是由Looper類來實現的,它定義在frameworks/base/core/java/android/os/Looper.java檔案中。
先理解幾個概念:
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和Handler
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.
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(); } }
在run()方法中做了兩件事情,一是建立了一個Handler執行個體,二是通過Looper類使該線程進入訊息迴圈中。
主要方法簡介:
static void
loop() : Run the message queue in this thread.
static void prepare() : Initialize the current thread as a looper.
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。
幾點小結:
· Handler的處理過程運行在建立Handler的線程裡
· 一個Looper對應一個MessageQueue
· 一個線程對應一個Looper
· 一個Looper可以對應多個Handler
· 不確定當前線程時,更新UI時盡量調用post方法