一、Handler
1、构造方法
首先我们进构造方法看看:
public Handler() {
this(null, false);
}
嗯,没办法,只有继续跟进去了:
public Handler(Callback callback, boolean async) {
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()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
可以看到11行,通过Looper.myLooper()获取了当前线程保存的Looper实例,接着便获取一个Looper的消息队列mLooper.mQueue,这样我们的handler的实例就与我们Looper实例中MessageQueue关联上了。
2、发送消息
接着我们来看看常用的hander方法,首先sendMessage():
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
然后sendEmptyMessageDelayed()方法:
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
可以看到都指向同一个方法,又跟进去:
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
再进去:
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) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
最终你还是有底线的:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
好了,可以看到这里调用了MessageQueue.enqueueMessage()方法,再看看MessageQueue里面干了啥:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
这里就是一个单链表的插入操作。就是把信息给插入到消息队列中去。
看到这里不禁奇怪了,没有哪里看到有发送消息啊?不知还记得handler初始化时候,赋值了一个looper和一个MessageQueue对象吗?现在我们去Looper里面看看。
二、Looper
Looper主要是prepare()和loop()两个方法。
1、prepare
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(true));
}
sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。可以看到,在第5行,将一个Looper的实例放入了ThreadLocal,并且2-4行判断了sThreadLocal是否为null,否则抛出异常。这也就说明了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例,相信某些大兄弟还碰过这种问题。
2、构造方法
再来看看构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在构造方法中,创建了一个MessageQueue(消息队列)。
3、loop方法
几经转折我们来看到loop方法:
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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
又是这么长,不让人活了是不是!没事,我把重点挑出来看:
public static void loop() {
final Looper me = myLooper();
···
final MessageQueue queue = me.mQueue;
···
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
···
msg.target.dispatchMessage(msg);
···
msg.recycleUnchecked();
}
}
这样是不是简单多了!解释一下:
第2行:
public static Looper myLooper() {
return sThreadLocal.get();
}
方法直接返回了sThreadLocal存储的Looper实例,如果me为null则抛出异常,也就是说looper方法必须在prepare方法之后运行。
第4行:拿到该looper实例中的mQueue(消息队列)
7到19行:就进入了我们所说的无限循环。
8行:取出一条消息,如果没有消息queue.next()方法会一直阻塞,那么这个无线循环就一直阻塞在这里了。
(大家可以去查看MessageQueue的next()方法,可以发现next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞。当有新消息到来时候,next会返回这条消息并将其从消息列表中删除)
15行:使用调用 msg.target.dispatchMessage(msg);把消息交给msg的target的dispatchMessage方法去处理。Msg的target是什么呢?其实就是handler对象,下面会进行分析。
18行:释放消息占据的资源。
不知大家记得否,在我们跟踪handler的sendMessage()方法跟到底的时候enqueueMessage()这个方法里面:
msg.target = this;
这里把当前handler对象赋值给了msg的target;
终于,我们貌似通了,handler把消息给MessageQueue的消息队列保存,然后looper遍历这个MessageQueue队列,再用msg.target即handler实例把消息给发送出去!
这个时候我们可以发现如果你是在主线程当中创建的handler,那么你绑定的肯定是主线程的Looper,所以这里执行的代码是在主线程的Looper中,即你的handleMessage()方法会在主线程执行。
我们再看看handler里的dispatchMessage()方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
再看看handleMessage()方法:
public void handleMessage(Message msg) {
}
嗯?这是个空方法?对呀,最终我们创建handler的时候都是复写handleMessage方法,然后根据msg.what进行消息处理。
例如:
private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case value:
break;
default:
break;
}
};
};
到此我们整个流程算是大致解析完了。
这里还有一个问题,就是Looper什么时候创建的呢?handler最开始拿到looper对象时候并没有创建这个对象啊?
其实在app启动的时候,跟随这个线程就已经在后台创建了一个looper对象。
我们可以看看ActivityThread中main方法:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
···
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread(); //创建ActivityThread对象
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在第5行,创建了一个Looper对象,通过Looper构造方法创建一个MessageQueue对象,并将Looper对象存储在ThreadLocal集合中,供后面在Handler创建时获取对应的Looper对象(需注意拿到对应Looper对象也能拿到Looper对应的MessageQueue对象)
三、总结
在app启动时候就已经创建一个Looper对象和一个MessageQueue对象,然后在handler中拿到这2个对象,handler->MessageQueue->Looper;
1、Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。
2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。
3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。
5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。
handler负责发送消息,Looper负责接收Handler发送过来的消息,并直接把消息回传给handler本身,MessageQueue就是一个存储消息的容器。
参考:
Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
Android之handler篇