


Looper對象通過MessageQueue來存放消息和事件。一個線程僅僅能有一個Looper。相應一個MessageQueue。
下面是Android API中的一個典型的Looper thread實現:
//而默認情況下。線程是沒有消息循環的,所以要調用 Looper.prepare()來給線程創建消息循環,然后再通過。Looper.loop()來使消息循環起作用。
- 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();
- }
另,Activity的MainUI線程默認是有消息隊列的。
所以在Activity中新建Handler時,不須要先調用Looper.prepare()。
那么遇到了有多Low的問題呢:
項目中重寫了一個HandlerThread,然后定義了post方法。然后在主線程中例如以下實現:
AsyncHandler.post(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
// 一坨要異步運行的代碼******
Looper.loop();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
那么明眼人一看就看出問題來了 ,這代碼一跑異步代碼肯定運行不到啊。為啥呢。且看下prepare的實現:
/** 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()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
So,簡單,卻是問題~