文章目录
概述
先看一个Android中的HandlerThread
是如何使用Looper
的。
public class HandlerThread extends Thread {
@Override
public void run() {
......
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
......
Looper.loop();
......
}
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
}
在线程的run
方法中调用Looper
的prepare()
方法进行准备工作,准备之后就可以通过Looper.myLooper
获取到当前的线程的Looper
了。使用然后调用loop
方法进入循环处理。使用的时候非常简单。接下来分析Looper
的实现。
而且可以quit
来退出线程,quit
方法中获取当前线程的looper
,不为null
会调用looper
对象quit
方法退出。
Looper
prepare方法
先分析一下静态的方法prepare
。
public final class Looper {
······
public static void prepare() {
prepare(true);
}
······
}
对外的静态方法prepare
调用私用的带有参数的prepare
方法。
public final class Looper {
······
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));
}
······
}
参数quitAllowed
标识是否允许looper退出。
首先调用sThreadLocal
参数获取是否有Looper
。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
sThreadLocal
线程的本地对象,用于保存线程相关的变量。如果从sThreadLocal
获取Looper
对象不为null
,说明线程已经绑定了Looper,直接抛出异常。如果为从sThreadLocal
获取的Looper对象为null
,就创建一个Looper
,并设置到sThreadLocal
中。
public final class Looper {
······
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
······
}
Looper
的构造方法中创建MessageQueue
,用于保存消息处理。并保存当前的线程到mThread
变量中。
总结一下:
Looper.prepare()
会调用私有带有参数的prepare
方法- 在私有的带有参数的
prepare
方法中会创建Looper
对象,并添加到线程的本地对象中。 Looper
的构造方法中会创建MessageQueue
消息队列对象。
loop方法
public final