作为一个Android开发者,肯定是用过Handler的。
而Handler最常见的使用场景,就是在子线程里进行更新UI的操作了。
我最开始以为Handler就是帮助我们将线程切换到主线程(也就是UI线程),可是后来我发现Handler是可以切换到任意线程的,而切换到主线程只是Handler最常用的功能而已。
我们先来看下最常见的Handler写法:
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv.setText("World!");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(3000);
handler.sendEmptyMessage(0);
}
}).start();
}
这段代码我们开启了一个线程,然后睡眠了三秒,睡眠之后我们更新了TextView。如果我们直接在线程里写更新UI的代码,是会报错的,因为Android的UI操作是线程不安全的,于是我们就需要Handler将我们的操作切换到主线程中去。
那么我们今天分析源码的目的,就是看看Handler机制的流程是什么,里面做了些什么。
我们按照顺序来,上面的代码中,会执行到handler.sendEmptyMessage(0)这句话,我们跟进去看看:
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
它直接返回了sendEmptyMessageDelayed方法,我们看下sendEmptyMessageDelayed这个方法:
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
它返回了sendMessageDelayed方法,在看这个方法前,我们看下Message.obtain()是啥,为啥是obtain()而不是直接New一个:
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();
}
我们可以发现Message是一个链表,然后Android内部维护了一个消息池,可以减少我们直接New Message的情况,既然Android已经提供了消息池,那我们自己New浪费空间。
这里的逻辑我解释一下,Message是一个链表,sPool也是个链表,sPool里面套着一串Message,然后先把sPool赋值给Message,再把Message的next置为null,把flag清零,就相当于从sPool中取出头部的Message来赋值。
好了我们继续看sendMessageDelayed方法:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
这里修正了一下delayMillis小于零的情况,然后返回了sendMessageAtTime,注意这里sendMessageAtTime里的参数,将本来延时时间,改成了一个准确的事件。
我们继续跟进:
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);
}
这里我们先看到mQueue被赋值给了queue,那么mQueue肯定不是空的啊,我们看看mQueue是什么时候被赋的值:
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class 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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
我们发现mQueue是在Handler(Callback callback, boolean async)这个构造方法里被赋的值,并且我还发现new Handler()这个构造方法,其实也是调用了this(null, false),也就是Handler(Callback callback, boolean async)这个构造方法,好了,那我们继续看。
我们发现mQueue被赋了mLooper.mQueue,而mLooper是Looper.myLooper()返回的。
那我们看看myLooper()里做了啥:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
我们看到这个方法就是返回了sThreadLocal.get(),那ThreadLocal是啥,其实它就是一个存东西的,而且是根据线程来存东西。上网找了找它的描述:ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
也就是说,每一个线程中的mLooper是独立的,这就有趣了,我们可以隐约的察觉到什么。我们可以猜测一下,既然每个线程中的mLooper是独立的,那我们线程的沟通切换啥的,就根据mLooper来进行就好了。
我们发现下面有行代码:
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
它判断了一下mLooper是否为空,也就是是否被初始化,如果没有的话,就会抛出个异常。说不能创建Handler,因为你没有调用Looper.prepare()。那么问题来了,我们最开始那个例子,没有调用这个函数不也创建成功了吗?
这是因为程序在启动的时候,已经调用了Looper.prepare()这个方法,我们看下ActivityThread的main方法:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// 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();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
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方法。
好了,那我们现在来看看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));
}
我们发现它显示判断了一下当前线程是否已经存在了Looper,有的话就抛出异常,说一个线程只能有一个Looper。如果没有的话就new一个Looper然后放进这个线程里。
我们继续看看new Looper(quitAllowed)里面是啥:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我们发现,在这个构造方法里,新建了一个MessageQueue赋值给了mQueue,并且把当前的线程给了mThread。
至于MessageQueue是啥,我在这里贴上源码里的注释,并简单翻译下:
Low-level class holding the list of messages to be dispatched by a
* {@link Looper}. Messages are not added directly to a MessageQueue,
* but rather through {@link Handler} objects associated with the Looper.
*
* You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
上面大致的意思就是MessageQueue持有一串的messages,然后等着Looper来分发它们。并且messages不会被直接的加进MessageQueue里,而是需要Handler与Looper配合来完成操作。
好了,读到这里,我们继续回到sendMessageAtTime方法里,大家是不是已经忘了呢,是不是看的晕了呢,哈哈哈哈反正我很爽,你来打我呀!
我们继续读发现sendMessageAtTime方法返回了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);
}
我们发现第一句: msg.target = this,this指的是当前的Handler,那么msg.target是啥呢?
其实它就是一个Handler,也就是说在这里,把我们的Handler与Message关联起来了!
之后就是判断下是否要异步操作,然后返回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放进MessageQueue的过程,这里插入的操作逻辑大概是这样的:
判断表头是不是空的,是的话就直接插进头里;判断要执行的时间是不是最小的,是的话也把它插进头里;如果上面两个条件都不满足,那么就遍历一下链表,找个合适的位置插入。
好了,这个时候,我们的Message就放进MessageQueue里了,那么我们就这样结束了吗?当然没有!有进去就有出来啊!我们怎么才能把Message从MessageQueue里面取出来呢?
还记得我们之前讲的MessageQueue的描述吗,说它等着被Looper来分发,既然如此,我们看看Looper的源码:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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 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();
}
}
茫茫代码中,一眼就找到了这段代码,哈哈哈哈,loop方法就是用来分发MessageQueue里的Message的,并且我们也看到了,它是一个死循环,在使用完后记得用quit()来退出。顺带一提,Looper.loop()也是在ActivityThread的main()方法里调用开启的。
代码最开始就是判断一下Looper有没有被创建,有的话就开始了一个死循环来分发Message。我们看死循环里的代码,首先Message msg = queue.next()会去取queue里的Message,若是空的,那么就会阻塞住,直到有了Message进来,就会开始分发。
然后代码一路下来,我们看到一句msg.target.dispatchMessage(msg),从名字上也看的出来这是分发的方法了,那么target是什么呢,我们之前已经分析过了,就是我们的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是不是空的,如果不是空的,就调用handleCallback方法:
private static void handleCallback(Message message) {
message.callback.run();
}
也就是调用的msg的callback
然后如果msg.callback是空的,那么先判断mCallback是不是空的,如果不是空的,就调用的mCallback.handleMessage(msg)方法。
最后实在不行,再去调用自己的handleMessage(msg)方法:
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
这个方法是个空方法,需要我们自己去实现,这个方法也就是我们最开始例子里面的那个handleMessage方法。
好了,经过种种的调用逻辑,终于从最终的handler.sendEmptyMessage(0)方法,来到了handleMessage方法,结束了这个旅程。
总结一下:
首先Looper我们需要用prepare()创建,并用loop()开启,创建时Looper会和当前的线程关联,我们最开始的例子不用这样是因为程序执行时在主线程已经创建并开启过了。
然后我们创建一个Message,然后通过Handler的各种sendMessage方法发送出去(这里的各种send方法最后都会到同一个方法里,大家可以自己跟),然后进行MessageQueue的入队操作,并且这个时候,将Handler与Message关联起来了。
最后就是勤劳的Looper不断的取消息,没消息就等着,有消息就取出来交给Handler去分发处理。
结束:
这篇文章写的顺序就是我看源码的顺序,大家看的时候可以一边开着源码一边看。我觉得不是很难(可能我太垃圾),主要是理一个思路。
水平不高,大家可能看的云里雾里的,见谅。
不知道为什么,这篇文章写的我很开心,看源码也看的很开心,可能我女朋友太可爱了吧。