Handler: 用于线程间通信。
MessageQueue: 消息队列。
Looper: 轮询器。
Message:消息
1、在主线程中创建的handler,自动和当前的(主)线程的Looper绑定。
public Handler() {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");//所以如果创建handler前,Looper没有被创建,必须Looper.prepare(),否则抛出此异常。
}
mQueue = mLooper.mQueue;
mCallback = callback;
}
2、每个Looper对应一个MessageQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
3、主线程中默认创建一个Looper,也就同时有个MessageQueue(点这里)
4、调用Looper.prepare();实际就是在创建新的Looper
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");//每个线程中只能存在一个Looper
}
sThreadLocal.set(new Looper(quitAllowed));
}
5、有位面试官说,消息的发送和取出全是Looper在协调。这里看:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this;
sent = queue.enqueueMessage(msg, uptimeMillis);//显然,消息发送到队列中Looper并未参与
}
else {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}