android线程间的通信靠什么,主要靠Looper里面的消息队列,通过看ActivityThread即所谓的UI主线程,我们可以看到里面有这么一行的代码
final Looper mLooper = Looper.myLooper();即主线程启动的时候,默认就给我们创建了一个Looper了,我们再看看Looper.class里面有这么一段
public static MessageQueue myQueue() {
return myLooper().mQueue;
}
可以知道,Looper维护了一个消息队列。那么谁往消息队列里面发送消息和取消息来消费呢?用过handler的都知道,是handler,因为我们一般这么调用的handler的发送消息的方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
但是再看看Handler的源码
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最终是MessageQueue将message添加给了自己。那么谁又在哪里不断读取队列里面的消息呢。看看Looper的源码
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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();
}
}
可以看到,其实是Looper的looper方法在无限循环的读取MessageQueue里面的Message,读取后的Message又交给了msg.target.dispatchMessage(msg);这个target就是Handler了,然后在我们创建的Handler里面处理消息
mainThreadHander = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int what = msg.what;
//这里可以执行更新UI的操作
if (what == 0) {
String content = "Thread name:" + Thread.currentThread().getName() + "'s mainThreadHander get message";
Log.d(TAG, content);
tv_content.setText(content);
}
}
};
好的,我们总结一下:主线程ActivityThread里面创建了一个Looper,Looper里面包含了MessageQueue,Handler调用MessageQueue的enqueueMessage方法,将消息发送给MessageQueue,ActivityThread里面启动了Looper.loop();Looper不断的从MessageQueue里面取消息,不断的next,即消息队列的消息是先进先出的,取出的消息交给Handler来处理。