Handler相信安卓开发者都很熟悉了,平常在开发的时候应用场景很多,但是Handler到底是如何发送消息和接收消息的呢,它内部到底做了些什么工作呢,本篇文章就Handler来分析它的源码流程
在Handler中有多个发送消息的方法,以下为几个例子:
第一个不用多说直接发送消息的,延迟时间是0
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
第二个发送带有延迟的消息,如果delayMillis 是负数则设置为0
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
第三个发送消息排在消息队列的头部,等待处理
public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg) {
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, 0);
}
从源码可以看出来第一个和第二个方法都是调用sendMessageAtTime方法,而sendMessageAtTime方法调用的是enqueueMessage方法,所以它们调用的都是enqueueMessage方法
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
这里把Handler自身设置给target
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
这里queue不会为空
return queue.enqueueMessage(msg, uptimeMillis);
}
走到这里我们看到这个msg.target 就是当前Handler,这里之所以这样写是为了后面用于消息分发的,这里的queue不会为空,我们来看queue到底在哪里实例的
public Handler() {
this(null, false);
}
public Handler(@Nullable 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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
实例化MessageQueue对象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
在这里看到不仅MessageQueue在这里实例化并且Looper也是在这里实例化的,在这里有个疑问就是mQueue这样写会不会为空呢,带着这个疑问我们后面解答,我们先看Looper中的myLooper方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
发现是从ThreadLocal静态对象里面获取的Looper对象,再看下在哪里设置的呢
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");
}
设置Looper
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
对象创建
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在这里我们看下ThreadLocal是怎么设置和获取的,找到set方法和get方法
public void set(T value) {
获取当前线程
Thread t = Thread.currentThread();
获取 ThreadLocalMap 并且一个线程一个ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
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")
返回的就是Looper对象
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
在这里说明一下一个线程对应一个ThreadLocalMap 一个ThreadLocalMap 对应一个key和value值,key对应的是sThreadLocal,value对应的存储的Looper对象。接着在这里发现MessageQueue是在这里实例化的,这里有个prepare方法里面设置的,那到底在哪里调用的呢。熟悉Activity启动流程源码的童鞋都知道,最终Activity启动流程操作主要是在ActivityThread里面的,并且Android程序刚开始的入口是ActivityThread的main方法,所以我们查看main方法
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
AndroidOs.install();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
// Call per-process mainline module initialization.
initializeMainlineModules();
Process.setArgV0("<pre-initialized>");
关注此方法
Looper.prepareMainLooper();
.....
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
消息循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
我们看到在入口调用了Looper.prepareMainLooper方法,我们直接进入方法
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
在这里惊奇的发现调用了prepare方法,在下面判断中保证一个线程中只能有一个Looper对象,否则抛出异常。
走到这里做个总结:
在子线程创建Handler对象的时候必须先要调用Looper.prepare()方法,否则会报错
Looper对象的创建是在ThreadLocal存储的
在主线程中创建Handler对象不需要Looper.prepare()方法,因为程序在ActivityThread入口处已经调用
每个线程只能调用Looper.prepare方法一次,只能创建一个Looper对象,否则抛出异常
下面我们看消息循环和存储
从上面可以看出几乎所有的发送消息方法都会调用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");
已经退出,释放消息
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 {
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;
}
if (needWake) {
用于唤醒Looper.loop()的循环消息的否则就是阻塞等待
nativeWake(mPtr);
}
}
return true;
}
这个方法主要是用来存储消息队列的,并且通过时间进行有序排序,有了消息之后就通过nativeWake方法这个方法是底层实现的,这个方法是用通过JNI实现的,即在底层通过C实现的,底层在这里就不多说了,不是本篇主要内容。在上面我们在ActivityThread中main方法中调用了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();
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
死循环不断的获取队列中的消息
for (;;) {
关注此方法
Message msg = queue.next();
如果为空跳出循环
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 Observer observer = sObserver;
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
try {
调用Handler dispatchMessage方法
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
回收消息,从这里就可以用回收的消息,而不用重新new Messaged对象了,这就是Message.obtain()的好处,因为会重新拿来使用
msg.recycleUnchecked();
}
}
这个方法是个无限循环方法等待获取可以处理分发msg消息的,我们重点来看MessageQueue.next()方法
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;
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
唤醒消息循环线程,有就唤醒,没有则等待
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
记录当前时间
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的下一个为null
msg.next = null;
标记为使用
msg.markInUse();
返回
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
如果队列需要退出,调用方法销毁队列,并返回null
if (mQuitting) {
dispose();
return null;
}
下面主要是处理IdleHandler,用于空闲的时候处理不紧急事件
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);
}
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);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
这个方法很重要在这里主要是取出Message返回给Looper.loop()用做消息分发,现在来看Looper.loop()方法中调用的Handler dispatchMessage方法
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在这里如果Message 设置了callback 的话,则直接调用 message.callback.run()方法,如果有设置Handler的callback,则也进行分发,如果都没有的话,那就直接调用handleMessage(Message msg)方法。
做个总结:
MessageQueue中的enqueueMessage方法是用来存储消息的,把消息按照链表的结构方式进行时间排序,此时调用底层nativeWake方法唤醒循环线程发送完数据之后然后调用Looper.loop()方法
Looper.loop()方法中调用MessageQueue.next()取出消息,所以MessageQueue.next()方法负责进行消息出队操作,它会无限循环检查是否有到时间的消息,如果有则把他出队,如果没有则循环阻塞
Looper.loop()取到消息之后进行分发,然后消息回收
最后:
在这里多说几句为什么用链表结构的方式进行存储消息,而不用数组的方式呢,熟悉ArrayList源码的开发者都知道它里面其实就是以数组的方式进行存储数据的,而LinkedList是以节点的方式存储的,相当于二叉树结构的和链表结构类似,所以最终我们知道链接结构主要是增加删除效率高,而数组的方式则是查询的效率高