android looper介紹

 Android中的Looper類,是用來封裝消息循環和消息隊列的一個類,用於在android線程中進行消息處理。handler其實能夠看作是一個工具類,用來向消息隊列中插入消息的。 

(1) Looper類用來爲一個線程開啓一個消息循環。 
    默認狀況下android中新誕生的線程是沒有開啓消息循環的。(主線程除外,主線程系統會自動爲其建立Looper對象,開啓消息循環。) 
    Looper對象經過MessageQueue來存放消息和事件。一個線程只能有一個Looper,對應一個MessageQueue。 

(2) 一般是經過Handler對象來與Looper進行交互的。Handler可看作是Looper的一個接口,用來向指定的Looper發送消息及定義處理方法。 
    默認狀況下Handler會與其被定義時所在線程的Looper綁定,好比,Handler在主線程中定義,那麼它是與主線程的Looper綁定。 
mainHandler = new Handler() 等價於new Handler(Looper.myLooper()). 
Looper.myLooper():獲取當前進程的looper對象,相似的 Looper.getMainLooper() 用於獲取主線程的Looper對象。 

(3) 在非主線程中直接new Handler() 會報以下的錯誤: 
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() 
緣由是非主線程中默認沒有建立Looper對象,須要先調用Looper.prepare()啓用Looper。 

(4) Looper.loop(); 讓Looper開始工做,從消息隊列裏取消息,處理消息。 

    注意:寫在Looper.loop()以後的代碼不會被執行,這個函數內部應該是一個循環,當調用mHandler.getLooper().quit()後,loop纔會停止,其後的代碼才能得以運行。 

(5) 基於以上知識,可實現主線程給子線程(非主線程)發送消息。 

    把下面例子中的mHandler聲明成類成員,在主線程經過mHandler發送消息便可。 
    
    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.
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();
      }
}
相關文章
相關標籤/搜索