Android的消息机制主要指Handler的运行机制,因此这里就从Handler的基本使用开始说起吧。
Handler使用示例
在一个指定的线程中使用Handler方式如下:
new Thread() {
@Override
public void run() {
super.run();
Looper.prepare();
mHandlerThr = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, ">>>>>>>>>>>>>Child# mHandler--handleMessage--msg.what: " + msg.what);
//接收发送到子线程的消息,然后向UI线程中的Handler发送msg 0。
mHandler.sendEmptyMessage(0);
}
};
Log.d(TAG, ">>>>>>>>>>>>>Child# begin start send msg!!!");
//Activity中启动Thread,在Thread结束前发送msg 0到UI Thread。
mHandler.sendEmptyMessage(0);
Looper.loop(); //不能在这个后面添加代码,程序是无法运行到这行之后的。
}
}.start();
其中mHandler时在MainActivity中声明的:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, ">>>>>>>>>>>>>UI# mHandler--handleMessage--msg.what: " + msg.what);
//接收发送到UI线程的消息,然后向线程中的Handler发送msg 1。
mHandlerThr.sendEmptyMessage(1);
mCount++;
if (mCount >= 3) {
//由于mHandlerThr是在Child Thread创建,Looper手动死循环阻塞,所以需要quit。
mHandlerThr.getLooper().quit();
}
}
};
以上的例子展示了如何在子线程中启动Handler,并与主线程中的Handler通信。其中,子线程中创建新的handler之前,需要先调用如下代码
Looper.prepare();
接着再创建Handler:
mHandlerThr = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, ">>>>>>>>>>>>>Child# mHandler--handleMessage--msg.what: " + msg.what);
//接收发送到子线程的消息,然后向UI线程中的Handler发送msg 0。
mHandler.sendEmptyMessage(0);
}
};
最终,需要调用
Looper.loop();
启动Looper,检测消息并进行处理。
Handler消息机制基本原理
首先,了解一下Handler运行的基本流程。
Handler运行时,主要依赖Looper以及MessageQueue来运行。其基本流程如下图所示:
image.png
首先,调用Handler的post方法,或者sendMessage方法,在经过一系列的调用之后,最终都是调用MessageQueue的enqueueMessage方法将消息插入消息队列中。接着,Looper循环从消息队列中取出消息对象。最后调用相应的回调。
消息入队
接着,了解一下消息怎么插入消息队列并且如何获取下一个消息队列的。
先看下Hanlder中最终被调用的方法:
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);
}
可以看出来这里调用了enqueueMessag,所以接下来看看这个方法吧。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这个方法里主要做了两件事:
- 把当前的Handler对象赋给了Message对象的target属性
- 调用MessageQueue的enqueueMessage方法
接下去看看MessageQueue的enqueueMessage方法:
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(TAG, 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;
}
Message对象是一个单链表,这个函数里主要就是在这个链表中根据when字段找到合适的位置插入,以保证消息队列中的元素都是按照时间排好序的。
读取消息
消息的读取时在Looper的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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
这个方法开头通过myLooper(),这个暂时不管,先看看消息获取及分发流程。
通过MessageQueue的next方法获取当前需要处理的消息,然后调用Message对象中的target属性的dispatchMessage方法分发消息,这个target就是刚刚的handler对象。
因此具体的分发逻辑还得回到Handler中:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这里邮箱调用Message对象中的回调。接着是handler中的mCallback,这是创建Handler对象时,传给构造函数的回调。如果mCallback也不存在,就调用handleMessage方法了,这就是开头例子中的使用方式了。
ThreadLocal
从子线程中Handler的使用方法可以看到,需要先调用一个Looper.prepare()方法,才能创建成功创建Handler,否则无法成功创建。
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));
}
还有,在Looper.loop()方法中,先通过myLooper方法获取了一个looper对象,其源码如下:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这里都使用了ThreadLocal对象,那为什么要用ThreadLocal呢?这要从Handler的使用场景说起了。
Handler主要用于延时任务或者开启一个异步任务,在开启异步任务时,肯定是需要将Handler与一个线程绑定起来,而Looper运行在这个线程中,并且读取消息、分发消息的逻辑都在Looper中,即Handler的实现逻辑都在Looper中,因此就需要使用ThreadLocal将Looper与当前线程绑定。
那ThreadLocal怎么实现的呢?
其实每个Thread对象中都存在一个ThreadLocal.ThreadLocalMap对象threadLocals,ThreadLocal通过读取及设置threadLocals来实现
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
网友评论