一、Looper概述:
Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用,从消息队列里取消息,处理消息。
二、Looper API简述:
Looper
extends Objectjava.lang.Object | |
↳ | android.os.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.
Looper是用来为一个线程执行一个消息循环的,线程默认是没有循环消息与他们绑定到一块的,为了创建一个,在线程中调用prepare()来运行这个循环,然后开始循环处理消息,直到这个循环结束。
大多数与消息循环交互是通过Handler()。
下面通过一个典型的线程循环的例子来说明,使用prepare()和loop()来创建一个handler来与
Looper交互。
常用方法:
loop()
在线程中执行消息队列,在结束时通过调用quit()。 注:写在Looper.loop()之后的代码不会被立即执行,当调用后mHandler.getLooper().quit()后,loop才会中止, 其后的代码才能得以运行。Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个 MessageQueue。
prepare()
为当前线程提供一个Looper.
getMainLooper()
返回当前应用程序中依赖主线程的looper,
getThread()
返回和looper相关联的线程。
mylooper()
返回和当前线程关联的looper,如果没有looper与当前线程关联,则返回null。
myQueue()
返回和当前线程相关联的消息队列,使用这个方法,必须确保当前线程与looper相关联。
prepareMainLooper()
初始化与主线程相关联的looper。
大多数与消息循环交互是通过Handler()。
下面通过一个典型的线程循环的例子来说明,使用prepare()和loop()来创建一个handler来与
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();
}
}
常用方法:
loop()
在线程中执行消息队列,在结束时通过调用quit()。 注:写在Looper.loop()之后的代码不会被立即执行,当调用后mHandler.getLooper().quit()后,loop才会中止, 其后的代码才能得以运行。Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个 MessageQueue。
prepare()
为当前线程提供一个Looper.
getMainLooper()
返回当前应用程序中依赖主线程的looper,
getThread()
返回和looper相关联的线程。
mylooper()
返回和当前线程关联的looper,如果没有looper与当前线程关联,则返回null。
myQueue()
返回和当前线程相关联的消息队列,使用这个方法,必须确保当前线程与looper相关联。
prepareMainLooper()
初始化与主线程相关联的looper。
三、如何创建Looper线程
当你的线程想拥有自己的MessageQueue的时候先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();
}
}
使线程拥有自己的消息列队,主线程拥有自己的消息列队,一般线程创建时没有自己的消息列队,消息处理时就在主线程中完成,如果线程中使用Looper.prepare()和Looper.loop()创建了消息队列就可以让消息处理在该线程中完成