引言
Handler机制是Android消息机制,是非常重要的需要深刻认识的基础知识,在日后的开发中需要被频繁用到的知识。
Handler机制中涉及Handler ,Looper,MessageQueue,Message
接下来就让我们从整体到局部的逐个说明下他们的关系
整体架构
Handler,MessageQueue,Message,Looper
四者之间的关系如下
Looper 是整体的老大,负责循环整个消息Message,MessageQueue则是Message的容器,而Handler不过是Android为了开发者封装出来的一个用于消息创建,发送消息,消息事件回调的一个类。
开始
我们从Android使用消息机制来说整个Handler机制的运行过程。
![](https://img.haomeiwen.com/i1180784/9e892fa480f8a3e1.png)
如果所示表明了在main()
中开始了这一消息之旅,那么Looper.loop()
方法做了什么呢,我们接着看源码
/**
* 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(); //1
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; //2
// 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 (;;) { //3
Message msg = queue.next(); // might block //4
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); //5
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(); //6
}
}
Looper的looper()方法主要是注释的6个点以下将逐一介绍
- 注释1 中的
Looper me = myLooper()
这里是为了获取到Looper这个对象,那我们去看下myLooper()
方法到实现 如下
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这里说明了是从sThreadLocal.get();
中获取那么 这里的THreadLocal又是什么鬼?答:ThreadLocal是Java中用于对不同线程存储变量的一个类,类似一个Map的存储类(key为对应对线程,value为存储的值),那么sThreadLocal是什么时候赋值的 在上图中往上看可以看到在Looper.loop()
方法之前有调用Looper.prepareMainLooper();
这里就是对Looper进行赋值,将当前线程与Looper进行绑定。内部方法如下
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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));
}
这样就完成了Looper的绑定。这里也说明了为什么在一个新的线程里为什么不调用Looper.prepare();直接使用Looper.loop()会crash,答案在如下代码中(新的线程里没有Looper所以肯定会报错)
final Looper me = myLooper(); //1
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
- 注释2 就是获取当前Looper的MessageQueue (稍后会讲解这个类的作用)
- 注释3 就开始Looper的死循环 (这里为什么不会导致程序的ANR? 这里为什么会导致程序的ANR,要对ANR有一个详细的了解,稍后会有一篇文章讲解什么是ANR,为什么会一些操作导致ANR,而不是什么死循环都会导致ANR)
- 注释4 就是从MessageQueue中获取对应的下一个Message,这里注意到在源码注释上 有一句 // might block 意思是可能会阻塞 这里我们需要深入的去看下源码 (这里的解释就直接在代码后面以注释的形式进行讲解)
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) { //这里发现MessageQueue也是一个死循环
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//这是JNI的方法,在JNI层等待被调用唤醒 就是这里可能会导致阻塞,因为在JNI层等待下一个消息
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages; //获取一个Message,
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg; //返回Message交给Looper处理
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
//如果没有消息了则返回null,并退出
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
//处理注册的IdleHandler,当MessageQueue中没有消息的时候,Looper会调用IdleHandler进行一些工作,例如垃圾回收等。
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
- 注释5 就是将当前执行的消息事件回调出去,这里target就是Handler。
- 注释6 则是将当前消息进行回收
以上就是
Looper.loop();
方法的说明,也是Looper核心方法
接下来就是讲一个Handler,Message,MessageQueue类
Handler
Handler 我个人觉得它是Android给开发者的一个辅助类,它封装了消息的投递,消息处理回调
构造函数(一切的开始)
-
public Handler() { this(null, false); }
-
public Handler(Callback callback) { this(callback, false); }
-
public Handler(Looper looper) { this(looper, null, false); }
-
public Handler(Looper looper, Callback callback) { this(looper, callback, false); }
-
public Handler(boolean async) { this(null, async); }
-
实现1
public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
-
实现2
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;
}
最终都是调用了6,7这两个就是将 mLooper,mQueue,mCallback,mAsynchronous 这四个赋值没啥说的
Handler其他的方法就是 obtainMessage(),sendMessage(),dispatchMessage()
没什么说的,大家看下源码就可以了
Message
小弟一样的角色,就是用来发送承载东西的类,也没什么说的
MessageQueue消息队列
消息队列用于处理获取消息和插入消息,整体是一个队列的形式
题外话-Android为什么为我们提供HandlerThread?
是因为我们写不明白吗?不 是Android考虑到我们写的不够周全
![](https://img.haomeiwen.com/i1180784/73fcc6d0eadb21c1.png)
那么这里就有一个问题因为是不同线程,执行的先后顺序无法保证 是先跑HandlerThread2.run()方法吗?很不确定,这个时候mLooper就不一定赋值了,所以这个时候就会出现问题。所以系统为我们周全的写了一个HandlerThread。就是为了解决这个问题 HandlerThread是通过锁机制来获取的。具体可以看下源码。
最后
这就是我理解的Handler机制,如果哪里有错,欢迎指出来
参考Android源码,《深入理解Android》卷1·第五章,《深入理解Android》卷2·第二章
网友评论