Handler有7个构造方法,常用的有:
public Handler() {
this(null, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
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实例
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.prepare()初始化Looper对象,然后必须调用Looper.loop()方法;
在主线程中创建时,会从ThreadLocal中获取mainLooper实例。
发送消息常用的方法,还有其他重载的方法,这里不再列举出来:
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
这些方法都会调用sendMessageDelayed(msg,delayMillis)
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
总结:handler.sendMessage(msg)其实只是把我们的Message加入了消息队列,队列采用的
是链表的方式,按照 when 也就是时间排序。没做其他逻辑了。
处理消息的方法,在looper实例的loop()方法里被调用的:
public void dispatchMessage(Message msg) {
//若msg.callback不为空,则代表使用了post(Runnable r)发送消息
//此时执行handleCallback(msg),即回调Runnable对象里复写的run()
if (msg.callback != null) {
handleCallback(msg);
} else {
//handler实例的回调不为空
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//执行到这里,说明handler实例的回调为空,
//此时执行handleMessage(msg)方法,
//创建Handler实例时复写的方法
handleMessage(msg);
}
}
Handler分析完了,接着看Looper类,其构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper的构造方法里初始化了消息队列,也获取当前的线程,从这里可以看出,Looper是与线程绑定的,且一个前程只有一个looper实例。
获取子线程的looper实例:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
获取主线程的looper实例:
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
Looper类中最重要的就是消息循环方法:
public static void loop() {
//获取looper实例
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//获取Looper实例中的消息队列对象(MessageQueue)
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//派发消息到对应的Handler,然后handler会处理消息
msg.target.dispatchMessage(msg);
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()方法不停的循环获取消息,将消息派发给handler处理。
MessageQueue类主要有两个方法,这里不做详细分析:
enqueueMessage(queue, msg, uptimeMillis):将消息插入消息队列
next():从消息队列中获取消息
至此,Handler相关源码分析完毕。