前言
是滴!我又来了...今天来讲讲老少皆宜的大名鼎鼎的handler。是的,想必handler这个东西已经被讨论的天花乱坠了,也经常被我们用在实际开发中,但是其中很多细节知识还是值得我们去学习深究的,比如,每个线程是怎么保证只有一个looper的,Message消息队列是通过什么实现的,handler.sendMessage()和handler.post()有什么区别,handler是怎么实现跨线程的消息传递等等。本篇也仅在源码的角度来探讨下其中的问题,水平有限,错误请及时指出。
文章可能比较长,请耐心阅读~
1.基本用法
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
//doSomething
super.handleMessage(msg);
}
};
Message message = Message.obtain();
message.what=1;
message.obj=new Object();
mHandler.sendMessage(message);
第二种就是post方式
new Handler().post(new Runnable() {
@Override
public void run() {
//doSomething
}
});
这里涉及的内存泄漏,先暂不讨论,我们先来看看Handler最基本的构造方法有哪些:
- Handler()
- Handler(Callback callback)
- Handler(Looper looper)
- Handler(Looper looper, Callback callback)
- Handler(boolean async)
- Handler(Callback callback, boolean async)
- Handler(Looper looper, Callback callback, boolean async)
我们看重载的最后两个构造方法就行,因为前面的几个也是依次调用到后的方法
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());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
一进来就是一个判断,眼尖的同学们可能看到了这个log,咦。。这个我好像见过...是的,当这个标志位位True的时候,这里会有一个校验的过程,如果不是静态的匿名,本地或成员类, 这类可能会产生泄漏,会有一个黄色的警告
接下来是mlooper的赋值,从Looper.myLooper()取出looper,如果为空的话,抛出一个异常。。相信这个异常同学们也多多少少遇到过...扎心了,点进myLooper()方法:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
咦。。这么简单吗,从ThreadLocal对象get出来一个looper,那么有get,当然有set,looper是什么时候set进去的呢?我们在Looper.prepare找到了答案
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方法时,当前sThreadLocal里面的looper不为空的话,直接抛出异常,这个异常也是蛮常见的...扎心,也就是保证了Looper.prepare()方法只当前线程能调用一次,注意是当前线程,至于ThreadLocal里面的逻辑先不讨论,后续我们展开再详细说,也就是从这里把looper给set进去了
所以在new handler的时候必须要先调用Looper.prepare()方法,当然,上面的例子是因为主线程中,ActivityThread类已经帮我们调用了,在子线程中创建handler的时候 需要手动调用Looper.prepare(),这里贴出部分ActivityThread代码,这里也是整个应用的入口,源码位置:/frameworks/base/core/java/android/app/ActivityThread.java,有兴趣的可以去看看
public static void main(String[] args) {
6042 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
6043 SamplingProfilerIntegration.start();
6044
6045 // CloseGuard defaults to true and can be quite spammy. We
6046 // disable it here, but selectively enable it later (via
6047 // StrictMode) on debug builds, but using DropBox, not logs.
6048 CloseGuard.setEnabled(false);
6049
6050 Environment.initForCurrentUser();
6051
6052 // Set the reporter for event logging in libcore
6053 EventLogger.setReporter(new EventLoggingReporter());
6054
6055 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6056 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6057 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6058
6059 Process.setArgV0("<pre-initialized>");
6060
6061 Looper.prepareMainLooper();
6062
6063 ActivityThread thread = new ActivityThread();
6064 thread.attach(false);
6065
6066 if (sMainThreadHandler == null) {
6067 sMainThreadHandler = thread.getHandler();
6068 }
6069
6070 if (false) {
6071 Looper.myLooper().setMessageLogging(new
6072 LogPrinter(Log.DEBUG, "ActivityThread"));
6073 }
6074
6075 // End of event ActivityThreadMain.
6076 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6077 Looper.loop();
6078
6079 throw new RuntimeException("Main thread loop unexpectedly exited");
6080 }
另外一个构造方法其实就区别于looper的赋值,一个是从当前线程ThreadLocal对象去取looper,一个是从外界赋值
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
2.发送消息
2.1 handler.sendMessage()
通过上面,我们的handler对象就创建出来了,接下来就是发送消息了,我们先来看看handler.sendMessage()到底干了啥:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
调用了sendMessageDelayed方法,传了一个0进去,接着看。。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
调用了sendMessageAtTime方法,传入了一个long的毫秒数,接着看。。
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);
}
这个也很清楚,把msg,uptimeMillis以及之前构造函数拿到的queue塞进去。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
把当前handler对象赋值给msg.target,调用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 {
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;
}
正主总算来了。。前面先校验一波,如果handler为空或者当前msg处于使用中,抛出异常。然后再持有MessageQueue.this锁,然后将Message放入队列中,整个流程可以分为几步:
- 如果当前队列为空,或者when等于0(也就是msg对应的时间点),或者msg时间点小于当前队列头部的p的时间点,就把我们传进来的msg放入队列首部,否则执行第二步
- 一个for的死循环,遍历队列中Message,找到when比当前Message的when大的Message,将Message插入到该Message之前,如果没找到则将Message插入到队列最后
- 判断是否需要唤醒,这里可以理解为,如果队列没有消息时,当前线程让出cpu资源,处于一种阻塞状态,当有消息到达时,需要唤醒next()函数,具体涉及到jni,后续详细分析
由此我们可以看出来整个队列消息结构是一种链表形式的,这样只要无限轮询消息,就能够轻易遍历除队列中所有消息
image2.2 handler.post()
第二种handler发消息方法 :
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
咦。。我们发现还是调用的sendMessageDelayed方法,只不过通过getPostMessage方法将Runnable对象转化为了msg对象
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
注意这里的callback,这里message对象的callback就不为空了,上述handler.sendMessage()方法的message对象的callback是为空的,后续再回调消息中会用到。
3.轮询消息
我们知道,android是基本消息机制的,主线程所有的行为都是由消息机制驱动的,比如activity的什么周期,点击事件等等。。。就主线程来说,在上面ActivityThread类中6077行可以看到Looper.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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
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();
}
}
代码基本能看清楚,一个for死循环,不断的queue.next(),从队列里取出消息,然后调用msg.target.dispatchMessage(msg),这里的target应该很清楚了,也就是handler对象,可以对照上面enqueueMessage方法,也就是拿到消息后,回调了到handler的dispatchMessage方法,我们接着看:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
终于到这了,相信同学们也已经很清楚。分几种情况:
- 首先来判断msg的callback是否为空,这个在哪里赋值的呢,对的,对应上面第二种也就是handler.post()形式的传进来的Runnable对象:
private static void handleCallback(Message message) {
message.callback.run();
}
然后回到到run()方法里面去,如果为空走第二种情况
- 又是一个判断如果mCallback不为空的话,回调handleMessage方法,这里的mCallback是在handler构造函数赋值的,对应下面的使用用法,但一般这种用法比较少,否则走第三步
new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
- 执行我们最终的handleMessage(msg)方法,也就是我们复写的handleMessage(msg)方法,对应我们上面的第一种用法
到此整个流程也基本大致走完了,一步一步来也是蛮easy的嘛,以后再遇到handler的时候,不管是使用或者面试的时候,自己心里也有点底
当然,里面还有很多细节,考虑到本文篇幅,就不多赘述了,比如,looper.loop()为什么不会导致ANR呢,Threadlocal的机制是什么样的等等,分析起来就比较耗时了,后续系列会跟大家再一起进行探讨!
溜了溜了...感谢看到结尾,谢谢~~
网友评论