在Android 系统中通常都说有四大组件:Activity,Service,Broadcast和Content Provider,但是还有两个最重要的东西是支撑整个Android 系统的进程间通信和线程间通信:Binder和消息队列。
Binder,是Android 系统使用的进程间通信,不论是应用层Java代码编写的进程还是C/C++编写的native进程都是通过Binder进行进程间通信的,Binder通信的实现也是很复杂,牵扯到驱动,runtime,native和Java Service,最基本的实现是通过进程间的共享内存来实现的,我们这次不讨论Binder。
消息队列,主要负责整个Android系统中消息的处理和分发,比如整个Android 系统InputManagerService就是依赖于Handler机制实现的,以及不同线程间通信的桥梁。
重要的几个类
-
Looper: 不断循环执行(
Looper.loop
), 按分发机制将消息分发给目标处理者 -
Handler: 消息辅助类,主要功能是向消息池发送各种消息事件(
Handler.sendMessage
)和处理相应的消息事件(Handle.handleMessage
) -
MessageQueue: 消息队列的主要功能是向消息池投递消息(
MessageQueue.enqueueMessage
)和取走消息池的消息(MessageQueue.next
) -
Message: 消息分为硬件产生的消息(如按钮,触摸)和软件生产的消息
这几个类在源代码的位置:
framework/base/core/java/andorid/os/
- Handler.java
- Looper.java
- Message.java
- MessageQueue.java
类的框架图:
![](https://img.haomeiwen.com/i5439660/af0777b0e72b962e.png)
-
Looper有一个MessageQueue消息队列
-
MessageQueue有一组待处理的Message
-
Message中有一个用于消息处理的Handler
-
Handler中有Looper和MessageQueue
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();
}
}
可以看到LooperThread是一个子线程,在这个线程的run
方法中有实现了Handler的handleMessage
方法,这个方法就是用来接收消息然后做相应的处理,主线程就可以通过LooperThread
的mHandler
来发送消息到子线程中,从而实现线程间通信。
下面就围绕着这段代码来解析一下源代码
Looper
Looper.prepare()
代码里面直接调用的是Looper.prepare()
,默认调用的是prepare(true)
,标识的是这个Looper允许退出,false则表示不允许退出。
// sThreadLocal.get() will return null unless you've called 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));
}
这里的sThreadLocal是ThreadLocal类型。
ThreadLocal: 线程本地存储区(Thread Local Storage, 简称为TLS),每个线程都有自己的私有本地存储区域,不同线程之间彼此不能访问对方的TLS区域。
ThreadLocal的get()
和set()
方法操作的类型都是泛型,
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
可见sThreadLocal通过get和set的是Looper
类型。
Looper.prepare()
在每个线程中只允许执行一次,该方法会创建Looper对象,Looper的构造方法中会创建一个MessageQueue对象,再通过Looper对象保存到当前线程的TLS。
Looper构造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); //创建MessageQueue对象
mThread = Thread.currentThread(); //记录当前线程
}
Looper.loop()
public static void loop() {
final Looper me = myLooper(); //从TLS中获取当前Looper对象
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; //获取Looper对象中的消息队列
// 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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) { //进入loop的主循环
Message msg = queue.next(); //可能会阻塞,取决于消息池中有无可用消息
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;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
//用于给target分发消息使用
msg.target.dispatchMessage(msg);
//记录分发消息用了多长时间
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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);
}
//讲Message放入到消息池来循环利用
msg.recycleUnchecked();
}
}
loop()
进入循环,不断的重复下面的操作,知道MessageQueue.next()
方法返回的是null
-
读取MessageQueue的下一条Message
-
把Message分发给相应的target
-
再把分发后的Message回收到消息池,以便重复利用
消息处理的核心部分就干这么几件事情,
Looper.quit()
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
最终是调用到MessageQueue.quit()
方法
void quit(boolean safe) {
//当mQuitAllowed为false,标识不允许退出,调用quit会抛出异常
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
//移除尚未触发的所有消息
removeAllFutureMessagesLocked();
} else {
//移除所有的消息
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
消息退出的方式有两种:
-
safe=true
时,只移除上位触发的所有消息,对于正在触发的消息不移除 -
safe=false
时,移除所有的消息
Looper.myLooper
用于偶去TLS存储的Looper对象
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
Handler
构造Handler
无参构造
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
//匿名类、内部类或本地类都必须申明为static,否则会警告可能出现的内存泄漏
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.prepare(),才能获取Looper对象,否则为null
mLooper = Looper.myLooper(); //从当前线程的TLS中获取Looper对象
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; //消息队列,来自Looper对象
mCallback = callback; //回调方法
mAsynchronous = async; //设置消息是否为异步处理方式
}
对于Handler的无参构造方法,默认采用当前线程TLS中的Looper对象,并且callback回调方法为null,且消息为同步处理方式。只要执行的Looper.prepare()
方法,那么便可以获取有效的Looper对象。
有参构造
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
Handler类在构造方法中,可指定Looper,Callback回调方法以及消息的处理方式(同步或异步),对于无参的Handler,默认是当前线程的Looper。
消息分发机制
在Looper.loop()
中,当发现有消息时,调用消息的目标handler,执行dispatchMessage()
方法来分发消息。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//当Message存在回调方法,回调msg.callback.run()方法
handleCallback(msg);
} else {
if (mCallback != null) {
//当Handler存在Callback成员变量时,回调方法handleMessage()
if (mCallback.handleMessage(msg)) {
return;
}
}
//Handler自身的回调方法handleMessage()
handleMessage(msg);
}
}
分发消息流程:
-
当
Message
的回调方法不为空时,则回调方法msg.callback.run
,其中callback数据类型为Runnable,否则进入步骤2 -
当
Handler
的mCallback
成员变量不为空时,则回调方法mCallback.handleMessage(msg)
,否则进入步骤3 -
调用
Handler
自身的回调方法handleMessage()
,该方法默认为空,Handler子类通过覆写该方法来完成具体的逻辑
对于很多情况下,消息分发后的处理方式是第3种情况,即Handler.hahndleMessage()
,一般往往通过覆写改方法从而实现自己的业务逻辑。
消息发送
发送消息调用流程
![](https://img.haomeiwen.com/i5439660/38e53fde15cf2269.png)
其实可以从图中看出,利用Handler
发送消息,最终调用到的是MessageQueue.enqueueMessage()
sendEmptyMessage
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
sendEmptyMessageDelayed
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
sendMessageDelayed
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
sendMessageAtTime
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);
}
sendMessageAtFrontOfQueue
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}
post
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
postAtFrontOfQueue
public final boolean postAtFrontOfQueue(Runnable r) {
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
enqueueMessage
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler.sendEmptyMessage()
等系列方法最终调用MessageQueue.enqueueMessage(msg, uptimeMills)
,将消息添加到消息队列中,其中uptimeMillis
为系统当前的运行时间。
Handler类还有一些其他的方法
-
obtainMessage
最终调用Message.obtainMessage(this)
,其中this为当前的Handler对象 -
removeMessage
Handler
是消息机制中非常重要的辅助类,更多的是实现MessageQueue, Message
中的方法。
MessageQueue
MessageQueue
是消息机制的Java层和C++层的连接纽带,大部分核心工作都是通过JNI中的native方法去实现的,涉及到下面列的方法:
private native static long nativeInit();
private native static void nativeDestroy(long ptr);
private native void nativePollOnce(long ptr, int timeoutMillis);
private native static void nativeWake(long ptr);
private native static boolean nativeIsPolling(long ptr);
private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);
创建MessageQueue
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
// 调用nativeInit获取底层的指针对象的地址mPtr,可以通过mPtr来调用底下native的接口
mPtr = nativeInit();
}
next()
获取下一条message
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) { //native层的指针对象被销毁之后就推出循环
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//调用底层阻塞函数nativePollOnce来等待消息的到来
//等待超时时间为nextPollTimeoutMillis,等待消息来唤醒
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;
}
}
nativePollOnce
是阻塞操作,其中nextPollTimeoutMillis
代表下一个消息到来前,还需要等待的时长,当nextPollTimeoutMills=-1
时,代表消息队列中没有消息,会无限等待下去。
当处于空闲时,会执行IdleHandler
中的方法,当nativePollOnce()
返回后,next()
从mMessages
中提取一个消息。
核心是nativePollOnce()
做的事情,底下通过epoll的机制实现。
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;
}
MessageQueue
是按照Message触发时间的先后顺序排列的,对头的消息是最早要触发的。当有消息要加入消息队列的时候,会遍历队列,寻找时间点插入要加入的消息,保证按照时间先后排序。
removeMessages
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
// 从头寻找符合条件的消息移除
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
// 移除剩余符合要求的消息
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
这个一出消息的方法,采用了两个while循环,第一个循环是从队头开始,移除符合条件的消息,第二个循环是从头部移除完连续的满足条件的消息后,再从队列后面继续查询会否有满足条件的消息需要移除。
postSyncBarrier
removeSyncBarrier
前面说每一个Message必须有一个target,对于特殊的message是没有target,即同步barrier token,这个消息的价值就是用于拦截同步消息,所以并不会唤醒Looper
Message
消息对象
每一条Message
的内容;
数据类型 | 成员变量 | 解释 |
---|---|---|
int | what | 消息类别 |
long | when | 消息触发时间 |
int | arg1 | 参数1 |
int | arg2 | 参数2 |
Object | obj | 消息内容 |
Handler | target | 消息响应方 |
Runnable | callback | 回调方法 |
创建一个新消息,就是去填充这些内容。
消息池
为了Message可以高效的重复利用,系统提供了消息池,当消息池不为空时,可以直接从消息池中获取Message
对象,而不是直接创建,提高效率。
静态变量sPoll
的数据类型为Message,通过next成员变量,维护一个消息池;静态变量MAX_POLL_SIZE
代表消息池的可用大小,消息池的默认大小为50
private static final int MAX_POOL_SIZE = 50;
消息池常用的操作方法是obtain()
和recycle()
obtain
从消息池中获取消息
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next; //从sPoll中取出一个Message对象
m.next = null; //断开消息链
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
recyle
把不用的消息放入消息池,循环利用
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
recycle()
,将Message加入到消息池的过程,都是把Message加到链表的表头。
总结
![](https://img.haomeiwen.com/i5439660/f6125e3ef7d5e955.png)
-
Handler通过sendMessage()发送Message到MessageQueue队列
-
Looper通过loop(),不断提取出达到触发条件的Message,并将Message交给target来处理
-
经过dispatchMessage()后,交回给Handler的handleMessage()进行相应的处理
-
将Message加入MessageQueue时,往管道写入字符,来唤醒loop线程;如果MessageQueue中没有Message,并处于Idle状态,则会执行IdleHanler接口中的方法,往往用于一些清理性的工作
消息分发的优先级
-
Message的回调方法:
message.callback.run()
-
Handler的回调方法:
Handler.mCallback.handleMessage(msg)
-
Handler的默认方法:
Handler.handleMessage(msg)
网友评论