Handler,Thread,Looper之間關系小結


http://blog.csdn.net/sunxingzhesunjinbiao/article/details/6794840

(1) Looper類別用來為一個線程開啟一個消息循環。默認情況下Android中新誕生的線程是沒有開啟消息循環的。(主線程除外,主線程系統會自動為其創建Looper對象,開啟消息循環)

Looper對象通過MessageQueue來存放消息和事件。一個線程只能有一個Looper,對應一個MessageQueue。

 

 

 

(2) 通常是通過Handler對象來與Looper交互的。Handler可看做是Looper的一個接口,用來向指定的Looper發送消息及定義處理方法。

默認情況下Handler會與其被定義時所在線程的Looper綁定,比如,在主線程中定義,其是與主線程的Looper綁定。

mainHandler = new Handler() 等價於new Handler(Looper.myLooper()).

Looper.myLooper():Return the Looper object associated with the current thread 獲取當前進程的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) 基於以上知識,可實現主線程給子線程(非主線程)發送消息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM