在整个Android的源码世界里,有两大利剑,其一是Binder IPC机制,,另外一个即是消息机制(由Handler/Looper/MessageQueue等构成的)。java
Android有大量的消息驱动方式来进行交互,好比Android的四剑客Activity
, Service
, Broadcast
, ContentProvider
的启动过程的交互,都离不开消息机制,Android某种意义上也能够说成是一个以消息驱动的系统。消息机制涉及MessageQueue/Message/Looper/Handler这4个类。缓存
MessageQueue.enqueueMessage
)和取走消息池的消息(MessageQueue.next
);Handler.sendMessage
)和处理相应消息事件(Handler.handleMessage
);Looper.loop
),按分发机制将消息分发给目标处理者。class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); //【见 2.1】 mHandler = new Handler() { //【见 3.1】 public void handleMessage(Message msg) { //TODO 定义消息处理逻辑. 【见 3.2】 } }; Looper.loop(); //【见 2.2】 } }
prepare(true)
,表示的是这个Looper容许退出,而对于false的状况则表示当前Looper不容许退出。
private static void prepare(boolean quitAllowed) { //每一个线程只容许执行一次该方法,第二次执行时线程的TLS已有数据,则会抛出异常。 if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } //建立Looper对象,并保存到当前线程的TLS区域 sThreadLocal.set(new Looper(quitAllowed)); }
sThreadLocal
是ThreadLocal类型,下面,先说说ThreadLocal。
ThreadLocal.set(T value)
:将value存储到当前线程的TLS区域,源码以下:public void set(T value) { Thread currentThread = Thread.currentThread(); //获取当前线程 Values values = values(currentThread); //查找当前线程的本地储存区 if (values == null) { //当线程本地存储区,还没有存储该线程相关信息时,则建立Values对象 values = initializeValues(currentThread); } //保存数据value到当前线程this values.put(this, value); }
ThreadLocal.get()
:获取当前线程TLS区域的数据,源码以下:public T get() { Thread currentThread = Thread.currentThread(); //获取当前线程 Values values = values(currentThread); //查找当前线程的本地储存区 if (values != null) { Object[] table = values.table; int index = hash & values.mask; if (this.reference == table[index]) { return (T) table[index + 1]; //返回当前线程储存区中的数据 } } else { //建立Values对象 values = initializeValues(currentThread); } return (T) values.getAfterMiss(this); //从目标线程存储区没有查询是则返回null }
sThreadLocal
变量,其定义以下:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>()
sThreadLocal
的get()和set()操做的类型都是
Looper
类型。
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); //建立MessageQueue对象. 【见4.1】 mThread = Thread.currentThread(); //记录当前线程. }
prepareMainLooper()
方法,该方法主要在ActivityThread类中使用。
public static void prepareMainLooper() { prepare(false); //设置不容许退出的Looper synchronized (Looper.class) { //将当前的Looper保存为主Looper,每一个线程只容许执行一次。 if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
public static void loop() { final Looper me = myLooper(); //获取TLS存储的Looper对象 【见2.4】 final MessageQueue queue = me.mQueue; //获取Looper对象中的消息队列 Binder.clearCallingIdentity(); //确保在权限检查时基于本地进程,而不是调用进程。 final long ident = Binder.clearCallingIdentity(); for (;;) { //进入loop的主循环方法 Message msg = queue.next(); //可能会阻塞 【见4.2】 if (msg == null) { //没有消息,则退出循环 return; } //默认为null,可经过setMessageLogging()方法来指定输出,用于debug功能 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); //用于分发Message 【见3.2】 if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } //恢复调用者信息 final long newIdent = Binder.clearCallingIdentity(); msg.recycleUnchecked(); //将Message放入消息池 【见5.2】 } }
logging == null
,经过设置setMessageLogging()用来开启debug工做。
public void quit() { mQueue.quit(false); //消息移除 } public void quitSafely() { mQueue.quit(true); //安全地消息移除 }
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(); //移除全部的消息 } //mQuitting=false,那么认定为 mPtr != 0 nativeWake(mPtr); } }
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
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; }
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对象【见2.1】 if (mLooper == null) { throw new RuntimeException(""); } mQueue = mLooper.mQueue; //消息队列,来自Looper对象 mCallback = callback; //回调方法 mAsynchronous = async; //设置消息是否为异步处理方式 }
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; }
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子类经过覆写该方法来完成具体的逻辑。MessageQueue.enqueueMessage()
;
public final boolean sendEmptyMessage(int what) { return sendEmptyMessageDelayed(what, 0); }
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) { Message msg = Message.obtain(); msg.what = what; return sendMessageDelayed(msg, delayMillis); }
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { return false; } return enqueueMessage(queue, msg, uptimeMillis); }
public final boolean sendMessageAtFrontOfQueue(Message msg) { MessageQueue queue = mQueue; if (queue == null) { return false; } return enqueueMessage(queue, msg, 0); }
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; }
public final boolean postAtFrontOfQueue(Runnable r) { return sendMessageAtFrontOfQueue(getPostMessage(r)); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); 【见4.3】 }
Handler.sendEmptyMessage()
等系列方法最终调用
MessageQueue.enqueueMessage(msg, uptimeMillis)
,将消息添加到消息队列中,其中uptimeMillis为系统当前的运行时间,不包括休眠时间。
public final Message obtainMessage() { return Message.obtain(this); 【见5.2】 }
Handler.obtainMessage()
方法,最终调用
Message.obtainMessage(this)
,其中this为当前的Handler对象。
public final void removeMessages(int what) { mQueue.removeMessages(this, what, null); 【见 4.5】 }
Handler
是消息机制中很是重要的辅助类,更多的实现都是
MessageQueue
,
Message
中的方法,Handler的目的是为了更加方便的使用消息机制。
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(boolean quitAllowed) { mQuitAllowed = quitAllowed; //经过native方法初始化消息队列,其中mPtr是供native代码使用 mPtr = nativeInit(); }
Message next() { final long ptr = mPtr; if (ptr == 0) { //当消息循环已经退出,则直接返回 return null; } int pendingIdleHandlerCount = -1; // 循环迭代的首次为-1 int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } //阻塞操做,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回 nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; //当消息的Handler为空时,则查询异步消息 if (msg != null && msg.target == null) { //当查询到异步消息,则马上退出循环 do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { //当异步消息触发时间大于当前时间,则设置下一次轮询的超时时长 nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // 获取一条消息,并返回 mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; //设置消息的使用状态,即flags |= FLAG_IN_USE msg.markInUse(); return msg; //成功地获取MessageQueue中的下一条即将要执行的消息 } } else { //没有消息 nextPollTimeoutMillis = -1; } //消息正在退出,返回null if (mQuitting) { dispose(); return null; } //当消息队列为空,或者是消息队列的第一个消息时 if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { //没有idle handlers 须要运行,则循环并等待。 mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } //只有第一次循环时,会运行idle handlers,执行完成后,重置pendingIdleHandlerCount为0. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; //去掉handler的引用 boolean keep = false; try { keep = idler.queueIdle(); //idle时执行的方法 } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } //重置idle handler个数为0,以保证不会再次重复运行 pendingIdleHandlerCount = 0; //当调用一个空闲handler时,一个新message可以被分发,所以无需等待能够直接查询pending message. nextPollTimeoutMillis = 0; } }
nativePollOnce
是阻塞操做,其中
nextPollTimeoutMillis
表明下一个消息到来前,还须要等待的时长;当nextPollTimeoutMillis = -1时,表示消息队列中无消息,会一直等待下去。
IdleHandler
中的方法。当nativePollOnce()返回后,next()从
mMessages
中提取一个消息。
nativePollOnce()
在native作了大量的工做,想进一步了解可查看 Android消息机制2-Handler(native篇)。
boolean enqueueMessage(Message msg, long when) { // 每个普通Message必须有一个target 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) { //正在退出时,回收msg,加入到消息池 msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { //p为null(表明MessageQueue没有消息) 或者msg的触发时间是队列中最先的, 则进入该该分支 msg.next = p; mMessages = msg; needWake = mBlocked; //当阻塞时须要唤醒 } else { //将消息按时间顺序插入到MessageQueue。通常地,不须要唤醒事件队列,除非 //消息队头存在barrier,而且同时Message是队列中最先的异步消息。 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; prev.next = msg; } //消息没有退出,咱们认为此时mPtr != 0 if (needWake) { nativeWake(mPtr); } } return true; }
MessageQueue
是按照Message触发时间的前后顺序排列的,队头的消息是将要最先触发的消息。当有消息须要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证全部消息的时间顺序。
void removeMessages(Handler h, int what, Object object) { if (h == null) { return; } synchronized (this) { Message p = mMessages; //从消息队列的头部开始,移除全部符合条件的消息 while (p != null && p.target == h && p.what == what && (object == null || p.obj == object)) { Message n = p.next; mMessages = n; p.recycleUnchecked(); p = n; } //移除剩余的符合要求的消息 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; } } }
public int postSyncBarrier() { return postSyncBarrier(SystemClock.uptimeMillis()); } private int postSyncBarrier(long when) { synchronized (this) { final int token = mNextBarrierToken++; final Message msg = Message.obtain(); msg.markInUse(); msg.when = when; msg.arg1 = token; Message prev = null; Message p = mMessages; if (when != 0) { while (p != null && p.when <= when) { prev = p; p = p.next; } } if (prev != null) { msg.next = p; prev.next = msg; } else { msg.next = p; mMessages = msg; } return token; } }
public void removeSyncBarrier(int token) { synchronized (this) { Message prev = null; Message p = mMessages; //从消息队列找到 target为空,而且token相等的Message while (p != null && (p.target != null || p.arg1 != token)) { prev = p; p = p.next; } final boolean needWake; if (prev != null) { prev.next = p.next; needWake = false; } else { mMessages = p.next; needWake = mMessages == null || mMessages.target != null; } p.recycleUnchecked(); if (needWake && !mQuitting) { nativeWake(mPtr); } } }
Message
表示,
Message
主要包含如下内容:
数据类型 | 成员变量 | 解释 |
int | what | 消息类别 |
long | when | 消息触发时间 |
int | arg1 | 参数1 |
int | arg2 | 参数2 |
Object | obj | 消息内容 |
Handler | target | 消息响应方 |
Runnable | callback | 回调方法 |
sPool
的数据类型为Message,经过next成员变量,维护一个消息池;静态变量
MAX_POOL_SIZE
表明消息池的可用大小;消息池的默认大小为50。
public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; //从sPool中取出一个Message对象,并消息链表断开 m.flags = 0; // 清除in-use flag sPoolSize--; //消息池的可用大小进行减1操做 return m; } } return new Message(); // 当消息池为空时,直接建立Message对象 }
public void recycle() { if (isInUse()) { //判断消息是否正在使用 if (gCheckRecycle) { //Android 5.0之后的版本默认为true,以前的版本默认为false. throw new IllegalStateException("This message cannot be recycled because it is still in use."); } return; } recycleUnchecked(); } //对于再也不使用的消息,加入到消息池 void recycleUnchecked() { //将消息标示位置为IN_USE,并清空消息全部的参数。 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) { //当消息池没有满时,将Message对象加入消息池 next = sPool; sPool = this; sPoolSize++; //消息池的可用大小进行加1操做 } } }
message.callback.run()
,优先级最高;Handler.mCallback.handleMessage(msg)
,优先级仅次于1;Handler.handleMessage(msg)
,优先级最低。