Android消息机制,主要指Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程。
Handler:主要作用是将一个任务切换到指定的线程中去执行。Android中UI控件不是线程安全的,所以在Android中不允许子线程访问UI,而当子线程需要访问UI时,Android提供了Handler来解决这个问题。
MessageQueue消息队列:存储消息列表,内部存储结构是单链表的数据结构
Looper循环:以无限循环的形式去查找是否有新消息,如果有就处理消息,如果没有就一直等待。
ThreadLocal的工作原理:
ThreadLocal是一个线程内部数据存储类,通过它可以在指定线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程则无法获取到数据。
Handler为什么要用到这个呢?因为对于Handler来说,需要获取到当前线程的Looper,而Looper的作用域就是当前线程,并且在不同线程有不同的Looper,这个时候可以方便的通过ThreadLocal对Looper进行存取。
大概了解ThreadLocal后,下面分析下ThreadLocal的内部实现,ThreadLocal是一个泛型类,只要弄清楚ThreadLocal的get()和set()方法就可以明白它的工作原理。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
set()方法中,首先是获取到当前使用这个ThreadLocal对象的线程,然后根据当前线程获取对应的ThreadLocalMap 对象,如果没有ThreadLocalMap 对象,则创建一个,如果有则把数据存入ThreadLocalMap 对象中。
getMap()方法返回的是Thread.threadLocals,在Thread内部我们发现threadLocals变量是用来存储ThreadLocal的数据,所以getMap()直接返回这个属性,当该属性为空时,通过createMap(t, value)来给Thread.threadLocals赋值。
/* ThreadLocal values pertaining to this thread. This map is maintained by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocalMap类是ThreadLocal类的一个静态内部类,在ThreadLocalMap内部有一个Entry[]数组,ThreadLocal存储的值就保存在这个数组里。Entry类是一个弱引用类,节省了内存。下面是table的存储规则
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
return;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
接下来看get()方法
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();
}
get()方法仍然是通过当前线程获取到ThreadLocalMap对象,然后获取之前存储的值,如果ThreadLocalMap对象为空,则使用默认值null
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
从ThreadLocal的set 和get 方法,它们所操作的对象都是当前线程ThreadLocalMap对象的Entry[] table数组,因此在不同线程中访问同一个ThreadLocal的set 和get 方法,它们对ThreadLocal所做的操作仅限于各自线程的内部。这也是为什么ThreadLocal可以在多个线程中互不干扰地存储和修改数据。
MessageQueue工作原理
MessageQueue消息队列,主要包含两个操作:插入和读取。enqueueMessage(Message msg, long when)往消息队列中插入一条消息,next()从消息队列中去除一条消息并将其从消息队列中一处。
boolean enqueueMessage(Message msg, long when) {
//判断Message是否绑定一个Handler对象(msg.target)
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) {
// 判断该消息是否正在退出,如果正在退出则回收当前消息并返回false
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; //第一次执行到这里时,mMessages为null
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;
//循环找到最后一个message
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;
}
next(),当消息队列里有消息时,则会取出这个message,即mMessages。当满足条件时,则取出这个mMessages(通过Message msg = mMessages赋值后返回msg),然后把mMessages赋值为msg.next,即把下一个消息赋值成mMessages。通过这个过程就把当前消息处理完了,并且把处理过的消息删除掉了。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
Looper的工作原理
Looper不断地从MessageQueue中查看是否有新消息,如果有新消息就立刻处理,否则就一直阻塞在哪里。Looper的构造函数中创建了一个MessageQueue,并且保存了当前线程。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Handler工作需要Looper,没有Looper线程会报错,那么如何为一个线程创建Looper呢?其实通过Looper.prepare()就可以为当前线程创建一个Looper,接着通过Looper.loop()方法来开启消息循环。
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对象保存到了ThreadLocal
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();
//死循环,
for (;;) {
Message msg = queue.next(); // might block
//当MessageQueue为空时,则跳出循环loop结束
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 {
//如果有消息,则把这个消息通过Handler(即msg.target)的dispatchMessage方法来处理这个消息,这样就成功将代码逻辑切换到制定线程中
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();
}
}
上述通过prepare方法和loop方法只是对普通线程来说的,对于主线程来说,由于主线程情况比较复杂,所以提供了prepareMainLooper来给ActivityThread创建Looper对象,但是其本质也是通过prepare来实现的,这个可以自己去看源码。同时,也可以通过getMainLooper方法在其他任何地方获取到主线程的Looper对象。
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Handler的工作原理
Handler的主要工作包含消息的发送和接收过程。消息的发送可通过一系列post、send方法来实现。
send.png post.png 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中插入了一条消息。MessageQueue的next()方法就会返回这条消息给Looper,Looper接收消息后就开始处理,最终消息由Looper交由Handler处理,即调用Handler的dispatchMessage方法,这是Handler就进入处理消息阶段。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
-----------------------------------------------------
private static void handleCallback(Message message) {
message.callback.run();
}
--------------------------------------------------------
Handler处理消息过程;
首先检查Messager的callback是否为null,,不为null就通过handleCallback来处理消息。 message.callback是一个Runnable对象,实际上就是Handler的post方法所传递的Runnable对象。其次,检查mCallback是否为null,不为null调用mCallback.handleMessage(msg)来处理消息,最后,调用handleMessage来处理消息。
总结
Android的消息机制的总体流程就是:Handler向MessageQueue发送一条消息(即插入一条消息),MessageQueue通过next方法把消息传给Looper,Looper收到消息后开始处理,然后最终交给Handler自己去处理。换句话说就是:Handler给自己发送了一条消息,然后自己的handleMessage方法处理消息,只是中间过程经过了MessageQueue和Looper。调用的方法过程如下:Handler.sendMessage方法–>Handler.enqueueMessage–>MessageQueue.next–>Looper.loop–>handler.dispatchMessage–>Handler.handleMessage(或者Runnable的run方法或者Callback.handleMessage)。
参考:android消息机制原理详解
《Android开发艺术探索》
网友评论