【Android】Handler机制源码详解(一)
今天初略学习了Android Handler消息传递机制,研究了一点源码。在此记录以备忘。
问:为什么看下面的源码:
答:
答:
在主线程发送消息,在子线程接收消息,Android中这种消息传递机制的实现需要像下面这样写;
而主线程接收,子线程发送消息就不需调用prepare(),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();
}
}
源码分析:
public class Handler {
final MessageQueue mQueue;
final Looper mLooper;
public Handler() {
this(null, false);0
}
public Handler(Callback callback, boolean async) {
//很多复杂的代码
mLooper = Looper.myLooper(); //获取当前线程的Looper对象
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; //将当前线程的Looper对象里的MessageQueue对象和本类的成员变量绑定
mCallback = callback;
mAsynchronous = async;
}
}
public class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); //每个线程和一个Looper绑定
final MessageQueue mQueue; //成员变量
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); //初始化MessageQueue
mThread = Thread.currentThread();
}
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)); //new一个Looper绑定在当前线程上
}
public static Looper myLooper() {
return sThreadLocal.get(); //拿出当前线程的Looper对象
}
}
- Looper.prepare()调用时候,关系1和关系2被建立。
- new Handler()时,关系3和关系4被建立。