Looper用于封装了android线程中的消息循环,默认状况下一个线程是不存在消息循环(message loop)的,须要调用Looper.prepare()来给线程建立一个消息循环,调用Looper.loop()来使消息循环起做用,从消息队列里取消息,处理消息。
注:写在Looper.loop()以后的代码不会被当即执行,当调用后mHandler.getLooper().quit()后,loop才会停止,其后的代码才能得以运行。Looper对象经过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
如下是Android API中的一个典型的Looper thread实现:
//Handler不带参数的默认构造函数:new Handler(),其实是经过Looper.myLooper()来获取当前线程中的消息循环, //而默认状况下,线程是没有消息循环的,因此要调用 Looper.prepare()来给线程建立消息循环,而后再经过,Looper.loop()来使消息循环起做用。
class LooperThread extends Thread java
{android
public Handler mHandler; 函数
public void run() oop
{ui
Looper.prepare();spa
mHandler = new Handler() .net
{线程
public void handleMessage(Message msg)code
{ 对象
// process incoming messages here
}
};
Looper.loop();
}
另,Activity的MainUI线程默认是有消息队列的。因此在Activity中新建Handler时,不须要先调用Looper.prepare()。
当你的线程想拥有本身的MessageQueue的时候先Looper.prepare(),而后Looper.loop();
参照源码:
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
|