Handler通信机制
首先,在分析
Handler
之前,我们必须先了解为啥需要Handler
,可以不需要Handler
吗?答案毫无疑问,当然是不行。我们知道在主线程是不能进行耗时操作的,子线程可以进行耗时操作但不能更新UI,那怎么办呢?只能子线程进行耗时操作,任务完成后,再通知主线程进行UI更新。其实更新UI只是一方面,Handler
最主要的作用是线程间的通信,所以我们需要了解去Handler
。
-
Handler
:负责消息的发送和处理; -
Looper
:负责消息的循环,即将消息从队列中取出,并发送给Handler处理; -
MessageQueue
:消息队列,负责消息的存放; -
Message
:消息,即信息的载体;
我们看下Google使用Handler
的方式
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
问题①:大家可以思考下为什么
Looper.prepare()
方法为什么一定要在Handler
之前调用?
我们将根据官方给出的示例,按照顺序分析。在线程的run()
方法中,先调用Looper.prepare()
方法,我们看下其源码
static final ThreadLocal<Looper> sThreadLocal = new 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");
}
sThreadLocal.set(new Looper(quitAllowed));
}
可以看到,在prepare()
方法中创建Looper
并加入到ThreadLocal
中,我们看下Looper
的构造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在Looper
的构造方法中可以看到,将初始化MessageQueue
并获得当前线程Thread.currentThread()
。大家看到这里,应该可以回答上面的问题①了。因为如果不先调用Looper.prepare()
方法,MessageQueue
将不会初始化,当Handler
发送消息到消息队列时为空,将会导致空指针异常。
下面,我们看下Handler
的构造
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
在构造方法中可以看到,将会获取Looper
,Looper
为空将会报错,并进行一些赋值操作。
继续看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();
for (;;) { // 1
Message msg = queue.next(); // 2
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 {
msg.target.dispatchMessage(msg); // 3
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();
}
}
代码很多,我们这里只看比较重要的1,2,3处。在1处,是一个for
无限循环;在2处,通过MessageQueue.next()
方法获取消息;在3处,调用msg.target.dispatchMessage(msg)
方法,将消息传给Handler
处理;我们看下Message
的target
是什么?
我们发现
target
是一个Handler
,那么我们在Handler
中看下这个方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
我们可以看到,最后调用的是handleMessage()
方法。毫无疑问,上面的Loop()
方法是从MessageQueue
中取出Message
交给handleMessage()
处理,那么Message
从何而来,或者说从哪儿将Message
加入到MessageQueue
中?当然是Handler
发送的消息的方法,我们看下
通过追踪,我们最后发现,它们最终调用的是
enqueueMessage()
方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在这里看到,Message
的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;//1
mMessages = msg;//2
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;//3
p = p.next;//4
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; //5
prev.next = msg;//6
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
方法里面的内容很多,其实通过1,2,3,4,5,6可以发现,主要的是将传过来的Message
进行赋值,赋值给MessageQueue
的mMessage
,达到保存消息的目的。
到这里,Handler
通信机制基本上分析完了,最后画了一张图进行一个总结
网友评论