Handler封装了消息的发送,也负责接收消。通过post方法和sendMessage发送消息。内部会跟Looper关联。
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public Handler(Looper looper) {
this(looper, null, false);
}
Looper 消息封装的载体,内部包含了MessageQueue,负责从MessageQueue取出消息,然后交给Handler处理 ,循环,默认线程是没有消息循环队列的,需要执行prepare或者prepareMainLooper方法创建Looper对象,调用loop开启消息循环。
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));
}
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
............
MessageQueue 就是一个消息队列,负责存储消息,有消息过来就存储起来,Looper会循环的从MessageQueue读取消息。MessageQueue包含了需要Looper处理的Message,MessageQueue不能直接添加Message而是通过Handler。 MessageQueue是由Looper初始化的时候创建的:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
源码地址:http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/os/Handler.java
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/os/Looper.java
关注公众号,获取更多开发必备知识