您的位置:首页 > 产品设计 > UI/UE

Android的消息机制(Handler、Looper、MessageQueue)

2017-02-09 15:26 399 查看
注:本文源码基于Android7.0

先大概概括一下消息机制:

这里有三个角色,Handler、looper、MessageQueue。Handler负责发消息和处理消息,Looper负责从MessageQueue中取出消息给Handler处理,MessageQueue则负责存储Handler发过来的消息。

这个机制主要是将一个任务切换到指定线程中执行,就像我们在子线程中更新UI界面,就可以用Handler。多说一句,特殊情况下子线程中也是可以更新UI的,具体可以看这篇文章,大概意思就是在ViewRootImpl未完全初始化之前更新Android
中子线程真的不能更新 UI 吗?。

我们从Handler的sendMessage方法入手开始分析:

public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
再看sendMessageDelayed方法

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}


再看sendMessageAtTime方法

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);
}
最后我们看enqueueMessage方法

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
从最后一行我们可以看出,Handler的sendMessage方法最终就是往MessageQueue里插入一条消息。

Looper我们就从Looper.prepare方法来分析

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));
}
prepare方法是为当前线程创建一个looper,从那个if语句中我们也知道了为什么一个线程中只能有一个Looper。sThreadlocal是Threadlocal类型,是一个线程内部的数据存储类,在该线程存储的数据只能在该线程中获取。

接下来我们看Looper.loop方法

public static void loop() {
//获取到当前的Looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//从Looper中得到MessageQueue
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();

//不断的从MessageQueue取消息,当没有消息时,next方法会阻塞,直到消息队列被标记为退出
//这样next方法会返回null
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

final long traceTag = me.mTraceTag;
if (traceTag != 0) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
//从这里看到了Handler的消息最终交给它的dispatchMessage方法来处理了
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐