构造
Handler的成员域包含有Looper和MessageQueue,如下:
public class Handler {
.....
final Looper mLooper;
final MessageQueue mQueue;
final Callback mCallback;
final boolean mAsynchronous;
IMessenger mMessenger;
....
public interface Callback {
public boolean handleMessage(Message msg);
}
}
在构造Handler的时候需要用初始化mLooper
,mQueue
,如果用户传入了Looper,就会用传入的Looper作为初始化参数,否则会以当前所现在线程的Looper为初始化参数,而用于初始化mQueue
的MessageQueue 参数是正是从用于初始化mLooper的Looper中来的。
//没有传入Looper的构造函数
public Handler() {
this(null, false);
}
//没有传入Looper的构造函数
public Handler(Callback callback) {
this(callback, false);
}
//没有传入Looper的构造函数
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,采用ThreadLocal来处理的
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的构造函数
public Handler(Looper looper) {
this(looper, null, false);
}
//传入Looper的构造函数
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
//传入Looper的构造函数
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
而Looper中的MessageQueue类型的成员域mQueue
则是在构造的时候被初始化的:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
显然Looper的构造函数为私有,要想初始化Looper,Looper提供了prepare()
和prepareMainLooper()
这两个静态方法,分别用于在当前线程和主线程中初始化Looper.
//当前线程初始化Looper
public static void prepare() {
prepare(true);
}
//主线程中初始化Looper,该方法会在ActivityThread的main方法中自动调用,不能我们自己方法中手动调用该方法
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {//只能初始化一次
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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));//此处在调用构造方法
}
当初始化以后,可以通过getMainLooper()
和myLooper()
静态方法分别拿到主线程的Handler和当前线程的Looper.
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
由于prepareMainLooper()
会在APP启动过程中通过ActivityThread的入口main方法中调用,因此再回到Handler的构造函数中,当我们在Activity或者Service中直接用new Handler()
或者其他不带Looper的构造函数或者传入的Looper是通过Looper.getMainLooper()
拿到的,该Handler只会处理主线程中的消息,该Handler中的Looper是由prepareMainLooper()
创建的,如此就将Handler、Looper和MessageQueue关联起来了。
发消息
Handler发消息最终会调用它的enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)
方法并将发送的消息和发送消息的Handler关联起来
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//将当前Handler对象绑定到后期处理消息的Handler上,当消息处理完成之后会调用 msg.target.dispatchMessage(msg);
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler在委托给MessageQueue 的boolean enqueueMessage(Message msg, long when)
方法,MessageQueue 会将消息按照时间先后顺序放入消息队列(实际上是一个单链表,插入和删除数据的代价会低一些,如果遍历只能从头到尾遍历)
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;
}
取消息
消息是在Looper的loop()
方法的一个无线循环中调用MessageQueue的next()
获取得到
public final class Looper {
...
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);//回调Handler的dispatchMessage方法
} 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();
}
}
...
}
现在我们需要知道Looper的loop()
方法何时调用,如果是在主线程中,则会在ActivityThread的入口函数中调用main调用,部分代码如下所示:
public final class ActivityThread {
...
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
.....
Looper.prepareMainLooper();//调用prepareMainLooper方法初始化主线程Looper
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();//调用loop方法(说明一直是阻塞在这里没有继续往下面执行,否则会抛出异常)
throw new RuntimeException("Main thread loop unexpectedly exited");
}
...
}
如果是在某一个子线程中,可遵照Handler的注释文档给出的形式,如下所示
class MyLooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
//如果要将该消息发送到主线程,在此处用主线程中的Handler 来发送,如:mUiHandler.sendMessage(msg);
}
};
Looper.loop();
}
}
Android提供了HandlerThread,无需手动调用loop()
,参见IntentService源码。
在MessageQueue的获取消息的next()
方法中,调用了一个java native方法private native void nativePollOnce(long ptr, int timeoutMillis)
,native的部分实现(参见MessageQueue.cpp):
static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
jlong ptr, jint timeoutMillis) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}
void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
mPollEnv = env;
mPollObj = pollObj;
mLooper->pollOnce(timeoutMillis);
mPollObj = NULL;
mPollEnv = NULL;
if (mExceptionObj) {
env->Throw(mExceptionObj);
env->DeleteLocalRef(mExceptionObj);
mExceptionObj = NULL;
}
}
不难看出调用的是native层的Looper类的pollOnce方法,参见(Looper.cpp)的pollOnce
方法,因里面用到著名的Linux的epoll机制,这一块我不太清楚因此目前没法继续深入下去了(o(╥﹏╥)o),先占个坑,希望以后能搞定
处理消息
由于处理消息是在Looper的loop()
方法调用Handler的dispatchMessage(Message msg)
方法,因此进入到Handler的这个方法签名下面:
public class Handler {
...
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
//这是需要重新覆盖的方法
public void handleMessage(Message msg) {
}
private static void handleCallback(Message message) {
message.callback.run();//callback是Runnable类型
}
...
}
不难看出,处理消息的时候,先看Message的callback是否存在,如果存在就用直接调用回调callback,如果不存在,检查Handler的成员域mCallback 是否存在,存在就回调,在构造一节可知mCallback是在构造函数中传入的,不再在就调用用户实现的handleMessage方法。
总结
Handler发送Message的实际只是将Message按照处理时间先后顺序存放到MessageQueue中并将发送的Message和该Handler相关联,在Looper的loop方法循环调用MessageQueue的next()获取可处理的Message,取出的Message在通过之前关联的Handler来处理。