前言
RTFSC (Read the fucking source code )才是生活中最重要的。我们天天就是要读懂别人的,理解别人的,然后再模仿别人的,最后才是创新自己的。人生大半的时间是在学习,所以我们一定要RTFSC
图例
图例就是消息机制的一个大概流程。Handler作为发送消息和接收处理消息的处理器;Message作为整个机制中传递的数据的载体;而MessageQueue作为消息队列,保存由Handler发送过来的数据。Looper是一个轮训器,会不断从MessageQueue消息队列中取出消息,然后交给Handler处理器来处理消息。当然一般发送消息和接收处理消息是在两个线程中进行的,所以这样一个流程就形成了一个异步机制。接下来进入源码逐步分析每一个类对象的作用和每一步的细节
Handler
首先可以看一下Handler的构造函数做了什么。不管调用哪个构造函数,可以看出最终都是调用其中实现了两个,和三个参数的构造函数。
两个参数的:
//Handler.java
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());
}
}
//赋值looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//从当前looper对象中获取消息队列对象,赋值mQueue 对象
mQueue = mLooper.mQueue;
//赋值回调接口
mCallback = callback;
mAsynchronous = async;
}
三个参数的:
//Handler.java
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
可以看出都是在做同样的事情,初始化Looper对象,MessageQueue对象以及回调接口(callback)。我们可以着重看一下两个参数的方法中mLooper = Looper.myLooper();
//Looper.java
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这里是从sThreadLocal中获取的一个looper对象,我们可以带着疑问去看看sThreadLocal是什么?
//Looper.java
static final ThreadLocal sThreadLocal = new ThreadLocal();
ThreadLocal类对象的引用
//ThreadLocal.java
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread
......
public class ThreadLocal {
......
}
注释已经很清楚的告诉了我们ThreadLocal类的作用是什么了。大致翻译:该类提供线程局部变量。这些变量不同于正常的对应关系,在每一个线程都都会增加一个。(通过它的get,set方法),独立的初始化变量....
意思就是一个线程有一个该对象的实例,用于保存线程的局部数据T。此处就是Looper对象。
再回到Looper中:
//Looper.java
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));
}
这里也看到了sThreadLocal.set(new Looper(quitAllowed));
Looper在准备阶段为sThreadLocal加入了一个Looper对象。然后在实例化Handler对象时会获取该对象。
......
//赋值looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
......
我们也可以从此代码片段看出,实例化handler对象之前需要调用Looper.prepare方法。否则会抛出RuntimeException("Can't create handler inside thread that has not called Looper.prepare()")。(tip:主线程在启动时已拥有了looper对象,所以可以直接实例化handler对象)
接下来可以看看hanlder发送消息的过程。
hanlder发送消息的方法很对,包括(sendMessage,sendEmptyMessage,sendEmptyMessageDelayed)等方法,但他们最后都会进入一个方法:
//Handler.java
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这里可以看到,消息把target设置成了当前handler对象(这里很重要,后面会提到),然后调用了消息队列的enqueueMessage方法。接下来进入MessageQueue中去看看enqueueMessage做了什么
MessageQueue
消息队列以链式结构保存着消息数据,接收保存Handler发送的消息,给looper提供消息用于处理消息。
//MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
......
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) {
//#1
// 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;
//#2
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;
}
#1
处是初始化链表头的过程,如果消息队列一条消息都没有的话,当然是将传入的消息作为表头。
#2
处是消息队列中已经存在数据的情况,因为此处只保存了表头,所以需要通过表头循环到链尾。将当前消息添加在链尾。
最后Looper.loop()会开启循环,处理消息
Looper
/**
* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {@link #prepare} in the thread that is to run the loop, and then
* {@link #loop} to have it process messages until the loop is stopped.
**/
该类被用来去循环运行一个线程的消息,线程默认没有消息循环(loop),在线程中通过prepare去创建一个looper,然后通过loop方法去开启消息处理。
//Looper.java
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();
//#1
for (;;) {
//#2
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 {
//#3
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);
}
#4
msg.recycleUnchecked();
}
}
#1
处开启消息循环,
#2
处从MessageQueue中获取一条消息(队列具有先进先出(FIFO)的特性)
#3
处将消息交给target的dispatchMessage方法处理。这里前面也提到过,消息的 target就是Handler处理器。所以此处可以到Handler的dispatchMessage方法中看看,是如何处理消息的:
//Handler.java
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
消息如果有回调,调用handleCallback(msg)方法,
private static void handleCallback(Message message) {
message.callback.run();
}
也就是调用了消息callback(Runnable接口回调)
继续上面的代码,如果mCallback不为空,回调mCallback 的消息处理方法,否则最后默认在Handler中的消息处理方法中回调处理。
然后回到Looper.loop方法中最后重要的一处
#4
处msg.recycleUnchecked();
,可以到Message中的recycleUnchecked()方法中看看:
//Message.java
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
首先是对消息的各项变量reset的一个过程,回到初始化状态。然后synchronized 中的同步代码块是做什么的呢?
其实就是把我们new过的消息,处理过后加入到一个消息池。该消息池也是一个单链表的数据结构。相当于此处是对消息的一种缓存机制。消息加入到消息池中后,Handler中的个obtain()方法就会从消息池中取消息,而不用重新实例化消息了。
//Message.java
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
此处可以清晰的看到,会先尝试从消息池中取消息。
总结
Handler提供了Android中线程通信的一种机制。用户可以在当前线程中创建一个handler实例,然后在子线程中通过handler发送消息,最后内部机制会回到handler所在的线程进行消息回调处理。整个流程就完成了异步消息的处理。
个人理解,如有错误请指出~
转载请注明出处
https://www.jianshu.com/p/b8dc22ba8fce