相信作安卓的不少人都遇到过这方面的问题,什么是异步消息机制,什么又是Handler
、Looper
和MessageQueue
,它们之间又有什么关系?它们是如何协做来保证安卓app的正常运行?它们在开发中具体的使用场景是怎样的?今天,就让咱们来揭开这几个Android异步消息机制中重要角色的神秘面纱。android
为何要学习Android异步消息机制?和AMS、WMS、View体系同样,异步消息机制是Android framework层很是重要的知识点,掌握了对于平常开发、问题定位和解决都是很是有帮助的,会使的咱们开发事半功倍。而要想成为一个合格的Android开发人员,光是懂得调用Android提供的那些个api是不够的,还要学会分析这些api背后的原理,知道它们是若是工做的,作到知其然亦知其因此然,若是不去学习技术背后的原理,只流于表面,这样永远都不会有进步,永远都只是一个Android菜鸟。git
Android中主线程也就是咱们所说的UI线程,能够简单理解为全部的界面呈现,能看获得的操做,全部的触摸、点击屏幕、更新界面UI事件的处理,都是在主线程中完成的。一个线程只有一条执行路径,若是主线程同时有多个事件要处理,那么是怎么作到有条不紊地处理的呢?接下来,以上提到的几个角色就要登场了,就是Handler+Looper+MessageQueue
这三个角色在起做用。github
Looper
是线程的消息轮询器,是整个消息机制的核心,来看看主线程的Looper
是如何建立的。api
主线程开启于 ActivityThread
的 main
方法中,来看一下 main
方法的源码。bash
public static void main(String[] args) {
、、、
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
、、、
}复制代码
Looper.prepareMainLooper()
这句代码彷佛为主线程建立 Looper
,进入方法内部一探究竟。微信
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));
}复制代码
果真在这个方法内部又调用 Looper.prepare(boolean)
方法为主线程建立 Looper
对象,存储在 ThreadLocal
中,咱们都知道,ThreadLocal
为每一个线程建立一个副本,因此不一样线程 set
的值不会被覆盖,再次取出值时对应的是该线程 set
进去的值。接下来经过 Looper.myLooper()
拿到主线程的 Looper
让Looper
的静态变量sMainLooper
持有,以后再想取主线程 Looper
经过 Looper.getMainLooper()
拿到并发
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}复制代码
这样,主线程的Looper
就建立成功了,须要注意的是,不管是主线程仍是子线程,Looper
只能被建立一次,不然会抛异常,以上源码能够很好地解释。app
与主线程稍稍有点不同,子线程的Looper
须要手动去建立,而且有些地方是须要注意的,下面让咱们一块儿来探究一下。less
子线程建立Looper
标准写法是这样的异步
new Thread(new Runnable() {
@Override
public void run() {
//建立子线程的Looper
Looper.prepare();
//开启消息轮询
Looper.loop();
}
}).start();复制代码
须要先建立子线程的Looper
再开启消息轮询,不然Looper.loop()
中会抛RuntimeException
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
、、、
}复制代码
这样,主线程和子线程的Looper
建立过程咱们都知道了,有了Looper
,咱们就能开启消息轮询了吗?不能,由于Looper
只是消息轮询器,就比如大厨,还须要食材才能烹饪,所以要想开启消息轮询,还须要消息的仓库,消息队列MessageQueue
。
咱们看看Looper
的私有构造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}复制代码
可见在每一个线程建立Looper
的时候也建立了一个MessageQueue
,并将MessageQueue
对象做为该线程Looper
的成员变量,这就是MessageQueue
的建立过程。
有了Looper
和MessageQueue
以后就能开启消息轮询了,很是简单,经过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();
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 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);
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(); } }复制代码
在方法中能够看到有一个for(;;)
死循环,该循环中又调用了MessageQueue
的next()
方法 ,进入方法一探究竟。
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 (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
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;
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;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
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.
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;
}
}复制代码
该方法里面一样有一个for(;;)
死循环,当没有能够处理该消息的Handler
时,就会一直阻塞
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}复制代码
若是从MessageQueue
中拿到消息,返回Looper.loop()
中,loop()
有如下片断
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}复制代码
能够很清楚看到Message
是用它所绑定的Handler
来处理的,调用dispatchMessage(Message)
,这个Handler
其实就是发送Message
到MessageQueue
时所用的Handler
,在发送时绑定了。
Handler
拿到消息以后会怎么处理呢,咱们暂且搁一边,先来看看Handler
是怎么建立并发送消息的
能够继承于Handler
并重写handleMessage()
,实现本身处理消息的逻辑
private static class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}复制代码
简单地,能够在程序中这样建立
MyHandler handler = new MyHandler();复制代码
须要注意的是,线程建立Handler
实例以前必须先建立Looper
实例,不然会抛RuntimeException
ublic 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;
}复制代码
Handler
的消息处理逻辑一样能够经过实现Handler
的内部接口Callback
来完成
public interface Callback {
public boolean handleMessage(Message msg);
}复制代码
Handler handler = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
//处理消息
return true;
}
});复制代码
关于这两种处理消息的方式哪一个优先级更高,接下来会讲到
首先能够经过相似如下的代码来建立Message
Message message = Message.obtain();
message.arg1 = 1;
message.arg2 = 2;
message.obj = new Object();复制代码
Handler
发送消息的方式多种多样,常见有这几种
sendEmptyMessage(); //发送空消息
sendEmptyMessageAtTime(); //发送按照指定时间处理的空消息
sendEmptyMessageDelayed(); //发送延迟指定时间处理的空消息
sendMessage(); //发送一条消息
sendMessageAtTime(); //发送按照指定时间处理的消息
sendMessageDelayed(); //发送延迟指定时间处理的消息
sendMessageAtFrontOfQueue(); //将消息发送到消息队头复制代码
也能够在设置Handler
以后,经过message
自身发送消息,不过最终都是调用Handler
发送消息的方法
message.setTarget(handler);
message.sendToTarget();
public void sendToTarget() {
target.sendMessage(this);
}复制代码
除此以外,还有一种另类的发送方式
post();
postDelayed();
postAtTime();
postAtFrontOfQueue();复制代码
以post(Runnable r)
为例,此种方式是经过post
一个Runnable
回调,构形成一个Message
并发送
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}复制代码
Runnable
回调存储在Message
的成员变量callback
中,callback
的做用,接下来会讲到
以上是消息的发送方式,那么消息是如何发送到MessageQueue
的呢,再来看
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
的 sendMessageAtTime()
,而且会检查消息队列是否为空,若空则抛 RuntimeException
,以后调用 Handler
的 enqueueMessage()
,最后调用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; }复制代码
该方法根据消息的处理时间来对消息进行排序,最终肯定哪一个消息先被处理
至此,咱们已经很清楚消息的建立和发送以及消息轮询过程了,最后来看看消息是怎么被处理的
回到Looper.loop()
中的这一句代码
msg.target.dispatchMessage(msg);复制代码
消息被它所绑定的Handler
的dispatchMessage()
处理了
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}复制代码
因而可知,消息处理到底采用哪一种方式,是有优先级区分的
首先是post
方法发送的消息,会调用Message
中的callback
,也就是Runnable
的run()
来处理
private static void handleCallback(Message message) {
message.callback.run();
}复制代码
其次则是看Handler
在建立时有没有实现Callback
回调接口,如有,则调用
mCallback.handleMessage(msg)复制代码
若是该方法没能力处理,则返回false
,让给接下来处理
最后才是调用Handler
的handleMessage()
Looper
,再有MessageQueue
,最后才是Handler
。Handler
,这些Handler
不管在哪里发送消息,最终都会在建立其的线程中处理消息,AsyncTask
、HandlerThread
等等都用到了异步消息机制。最后借用一张图说明Android异步消息机制
至此,Android 异步消息机制就讲解完毕了,有木有一种醍醐灌顶的感受,哈哈~~~~,这篇文章涉及到的源码不难,很是好理解,关键仍是要本身去阅读源码,理解其原理,作到知其然亦知其因此然,这个道理对于大部分领域的学习都适用吧,要知道,Android发展到如今,技术愈来愈成熟,早已不是那个写几个界面就能拿高薪的时代了,市场对于Android 工程师的要求愈来愈高,这也提醒着咱们要跟上技术发展的步伐,时刻学习,避免被淘汰。
因为水平有限,文章可能会有很多纰漏,还请读者可以指正,Android SDK 源码的广度和深度也不是小小篇幅可以归纳的,未能尽述之处,还请多多包涵。
欢迎关注我的微信公众号:Charming写字的地方
CSDN:blog.csdn.net/charmingwon…
简书:www.jianshu.com/u/05686c7c9…
掘金:juejin.im/user/59924e…
Github主页:charmingw.github.io/
欢迎转载~~~