image.png
looper介紹
Looper類別用來為一個線程開啟一個消息循環(huán)阅爽。
默認情況下Android中新誕生的線程是沒有開啟消息循環(huán)的。(主線程除外荐开,主線程系統(tǒng)會自動為其創(chuàng)建Looper對象付翁,開啟消息循環(huán))
Looper對象通過MessageQueue來存放消息和事件。一個線程只能有一個Looper晃听,對應一個MessageQueue百侧。
通常是通過Handler對象來與Looper交互的。Handler可看做是Looper的一個接口能扒,用來向指定的Looper發(fā)送消息及定義處理方法佣渴。
常用的方法:
方法 | 含義 |
---|---|
Looper.myLooper() | 獲取當前進程的looper對象。 |
Looper.getMainLooper() | 用于獲取主線程的Looper對象初斑。 |
常見錯誤
在非主線程中直接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()
原因是因為非主線程中默認沒有創(chuàng)建Looper對象辛润,需要先調用Looper.prepare()
啟用Looper。