Android消息机制是Android操做系统中比较重要的一块。具体使用方法在这里再也不阐述,能够参考Android的官方开发文档。java
消息机制的主要用途有两方面:编程
一、线程之间的通讯。好比在子线程中想更新UI,就经过发送更新消息到UI线程中来实现。缓存
二、任务延迟执行。好比30秒后执行刷新任务等。安全
消息机制运行的大概示意图以下:app
一个线程中只能有一个Looper对象,一个Looper对象中持有一个消息队列,一个消息队列中维护多个消息对象,用一个Looper能够建立多个Handler对象,Handler对象用来发送消息到消息队列中、和处理Looper分发给本身的消息(也就是本身以前发送的那些消息),这些Handler对象能够跨线程运行,可是最终消息的处理,都是在建立该Handler的线程中运行。 less
整个消息机制的一个重要用途,就是线程间通讯,并且大部分都是工做线程向主线程发送数据和消息。那么为何Android系统要这样设计呢?其实典型的Android应用,都是事件驱动的GUI程序,跟Window的GUI程序很相似。这种程序,特色就是基于事件运行,好比点击事件或者滑动事件。因此这种状况下,确定是要有一个专门的线程来负责事件的监听和分发。在Android中,系统默认启动的主线程,就干这个事情了。异步
因为该消息分发线程有着本身独特的任务,因此若是该线程阻塞了的话,系统就会出现无响应的状况。这样,天然就不可能把耗时的任务放在该线程中,因此官方推荐是把耗时的任务放到工做线程中执行。可是不少时候,耗时任务的执行结果,都是要反馈到UI上的。而Android中的View,是不能在非UI线程中更新的,由于View不是线程安全的,没有同步,因此必需要把数据经过线程间通讯的模式,发送到UI线程,这能才能够正常更新UI。async
因此你们会问,Android为何不把View设计成线程安全的呢?那么在Java这种指令式编程语言中,线程安全就是意味着要加锁。其实咱们能够思考一下,整个View响应事件,事件从屏幕产生,通过Framework,最后到kernel,而后kernel处理完成后,向上传递到framework,而后又传递到View层。以下图所示:编程语言
那么若是整个流程都是线程安全的话,就会面临着两个相对的加锁流程,这种反方向的加锁,很容易就会致使死锁的状况发生。这是绝大多数GUI系统存在的问题,因此绝大多数GUI系统都是采用事件分发机制来实现的。因此说Android为何设计成单线程模型了。ide
在熟悉了基本用法以后,有必要深刻探索一下。
Android消息机制的framework层主要围绕Handler、Looper、Message、MessageQueue这四个对象来操做。消息机制主要是对消息进行生成、发送、存储、分发、处理等操做。
该类表明的是消息机制中的消息对象。是在消息机制中被建立,用来传递数据以及操做的对象,也负责维护消息对象缓存池。
Message对象中主要有如下几个属性:
what:消息类型。
arg一、arg二、obj、data:该消息的数据域
when:该消息应该被处理的时间,该字段的值为SystemClock.uptimeMillis()。当该字段值为0时,说明该消息须要被放置到消息队列的首部。
target:发送和处理该消息的Handler对象。
next:对象池中该消息的下一个消息。
Message对象中,主要维护了一个Message对象池,由于系统中会频繁的使用到Message对象,因此用对象池的方式来减小频繁建立对象带来的开支。Message对象池使用单链表实现。最大数量限制为50。因此官方推荐咱们经过对象池来获取Message对象。
特别注意的是,咱们日常使用的都是普通的Message对象,也就是同步的Message对象。其实还有两种特殊的Message对象,目前不多被使用到,但也有必要了解一下。
第一个是同步的障碍消息(Barrier Message),该消息的做用就是,若是该消息到达消息队列的首部,则消息队列中其余的同步消息就会被阻塞,不能被处理。障碍消息的特征是target==null&&arg1==barrierToken
第二个是异步消息,异步消息不会被上面所说的障碍消息影响。经过Message对象的setAsynchronous(boolean async)方法来设置一个消息为异步消息。
该类表明的是消息机制中的消息队列。它主要就是维护一个线程安全的消息队列,提供消息的入队、删除、以及阻塞方式的轮询取出等操做。
该类表明的是消息机制中的消息分发器。 有了消息,有了消息队列,还缺乏处理消息分发机制的对象,Looper就是处理消息分发机制的对象。它会把每一个Message发送到正确的处理对象上进行处理。若是一个Looper开始工做后,一直没有消息处理的话,那么该线程就会被阻塞。在非UI线程中,这时候应该监听当前MessageQueue的Idle事件,若是当前有Idle事件,则应该退出当前的消息循环,而后结束该线程,释放相应的资源。
该类表明的是消息机制中的消息发送和处理器。有了消息、消息队列、消息分发机制,还缺乏的就是消息投递和消息处理。Handler就是用来作消息投递和消息处理的。Handler事件处理机制采用一种按自由度从高到低的优先级进行消息的处理,正常状况下,一个Handler对象能够设置一个callback属性,一个Handler对象能够操做多个Message对象,从某种程度上来讲,建立一个Message对象比给一个Handler对象设置callback属性来的自由,而给一个Handler对象设置callback属性比衍生一个Handler子类来的自由,因此消息处理优先级为Message>Handler.callback.Handler.handleMessage()。
重要部分的源代码解析,源代码基于sdk 23。
普通的消息对象,包含了消息类型、数据、行为。内部包含了一个用单链表实现的对象池,最大数量为50,为了不频繁的建立对象带来的开销。
源代码:
public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; m.flags = 0; // clear in-use flag sPoolSize--; return m; } } return new Message(); }
伪代码:
public static Message obtain() { synchronized (sPoolSync) { if (对象池不为空) { 从单链表实现的对象池中取出一个对象(从链表头获取); 清空该对象标志位(在使用中、异步等); 修正对象池大小; return 取出的消息对象; } } return 新建消息对象; }
源代码:
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++; } } }
伪代码:
void recycleUnchecked() { 标志为正在使用中; 清空当前对象的其余数据; synchronized (sPoolSync) { if (对象池没容量有达到上限) { 在单链表表头插入该对象; 修正对象池大小; } } }
使用ThreadLocal来实现线程做用域的控制,每一个线程最多有一个Looper对象,内部持有一个MessageQueue的引用。
源代码:
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)); }
伪代码:
private static void prepare(boolean quitAllowed) { if (当前线程中已经有了一个Looper对象) { throw new RuntimeException("一个线程只能建立一个Looper对象"); } 从新实例化一个能够退出的Looper; 把该Looper对象和当前线程关联起来; }
源代码:
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 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } 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(); } }
伪代码:
public static void loop() { 获取当前线程的Looper对象; if (当前线程没有Looper对象) { throw new RuntimeException("没有Looper; Looper.prepare() 没有在当前线程被调用过"); } 获取该Looper对象关联的MessageQueue; 清除IPC身份标志; for (;;) { 从MessageQueue中获取一个Message,若是当前MessageQueue没有消息,就会阻塞; if (没有取到消息) { // 没有消息意味着消息队列退出了. return; } 打印日志; 调用当前Message对象的target来处理消息,也就是发送该Message的Handler对象; 打印日志; 获取新的IPC身份标识; if (IPC身份标识改变了) { 打印警告信息; 回收该消息,放入到Message对象池中; } }
负责消息的发送、定时发送、延迟发送、消息处理等动做。
源代码:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
伪代码:
public void dispatchMessage(Message msg) { if (该消息的callback属性不为空) { 运行该消息的callback对象的run()方法; } else { if (当前Handler对象的mCallback属性不为空) { if (mCallback对象成功处理了消息) { return; } } Handler内部处理该消息; } }
使用单链表的方式维护一个消息队列,提升频繁插入删除消息等操做的性能,该链表用消息的when字段进行排序,先被处理的消息排在链表前部。内部的阻塞轮询和唤醒等操做,使用JNI来实现。
源代码:
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; }
伪代码:
boolean enqueueMessage(Message msg, long when) { if (该消息没有target) { throw new IllegalArgumentException("Message对象必需要有一个target"); } if (该消息正在被使用) { throw new IllegalStateException(msg + " 该消息正在使用中"); } synchronized (this) { if (消息队列退出了) { 打印警告信息; 回收该消息,返回到Message对象池; return false; } 设置该消息为正在使用中; 设置消息将要被处理的时间; Message p = mMessages; boolean needWake; if (msg队列为空 || 该消息对象请求放到队首 || 执行时间先于当前队首msg的执行时间(当前队列中全是delay msg)) { 把当前msg添加到msg队列首部; 若是阻塞了,设置为须要被唤醒; } else { if (阻塞了 && 队首是barrier && 当前msg是异步msg) { 设置为须要被唤醒 } for (;;) { 根据msg.when的前后,找到合适的插入位置,先执行的在队列前面; if (须要唤醒 && 插入位置以前有异步消息) { 不须要唤醒; } } 插入到合适的位置; } if (须要唤醒) { 调用native方法进行本地唤醒; } } return true; }
源代码:
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; } }
伪代码:
Message next() { if (消息队列退出了) { return null; } 把Idle事件的次数标记为第一次; 下一次轮询的等待(阻塞)时间设为0; for (;;) { if (下一次轮询须要阻塞) { 清楚Binder的pending command,用来释放资源; } 使用当前的设置轮询阻塞时间去作一次native的轮询,若是阻塞时间大于0,则会阻塞,直到取到消息为止; synchronized (this) { if (消息队列首部为barrier消息) { 取出第一个异步消息; } if (查询到知足条件的消息) { if (还没到该消息的执行时间) { 设置下一次轮询的阻塞时间为msg.when - now,最大不超过Integer.MAX_VALUE; } else { 阻塞标识设置为false; 取出该消息,重定向链表头; 标记该消息为在使用中; return 该消息; } } else { 没有消息,设置下一次轮询阻塞时间为-1,不阻塞; } if (消息队列退出了) { 释放资源; 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 (第一次Idle事件) { 计算Idle监听器数量; } if (没有Idle监听器) { 阻塞标识设置为true; continue; } 生成Idle监听对象; } for (int i = 0; i < pendingIdleHandlerCount; i++) { 通知Idle事件的监听对象,根据标识来肯定这些监听器是否继续监听。 } 设置Idle事件的标识为不是第一次; 调用了Idle监听器以后,可能有新的消息进入队列,因此下一次轮询阻塞时间设置为0; } }