Andorid消息机制主要是指Handler的运行机制,Handler的运行须要底层的MessageQueue和Looper的支撑。MessageQueue是消息的存储单元,Looper是对这个消息队列进行无限循环查询的操做人。数组
关于UI更新,Android规定不能在子线程更新UI,这是ViewRootImpl对UI进行的验证操做。安全
void checkThread() { if (mThread != Thread.currentThread()) { throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }
每次加载UI的时候ViewRootImpl对更新UI线程进行检查,不是的话则爆一个异常出来。async
所以UI更新的时候须要在主线程。可是在主线程有太多操做会致使ANR,所以复杂操做须要在子线程中进行。ide
问题来了,假如须要一个很复杂的操做,其中须要将最后的结果更新在UI中,咱们势必不能在主线程中进行了。此时须要一个能在子线程中与主线程进行沟通的桥梁,来协助咱们在子线程中,与主线程通讯,让主线程来更新UI。所以Android为咱们提供了Handler解决这个问题。函数
(系统之因此不让咱们在子线程中更新UI,是由于UI控件是线程不安全的,若被多个子线程操做更新UI,会致使各类问题。可是咱们加锁的话,又会由于粒度太粗致使UI访问的效率下降)oop
使用Handler的大体流程:post
一、首先建立一个Handler对象,能够直接使用Handler无参构造函数建立Handler对象,也能够继承Handler类,重写handleMessage方法来建立Handler对象。学习
二、Handler建立完毕以后,其内部的Looper以及MessageQueue就能够和Handler一块儿协同工做。咱们能够Post一个Runnabe对象投递到Handler内部的Looper中去处理,也能够经过Handler的send方法发送一个消息,这个消息一样给Looper去处理(Post最终也是使用的send)。三、当Handler的send方法被调用时,他会调用MessageQueue的enqueueMessage方法,将这个消息放入消息队列中,而后Looper一旦发现有新的消息时,就会自动处理这个信息,最终消息中的Runnable或者Handler的handleMessage方法会被调用。(因为Looper是在主线程中的,所以Handler的业务至关于给Looper去操做了,所以就是在主线程中进行的处理)。ui
-----------------------threadLocalthis
ThreadLocal是一个线程内部的数据存储类,咱们可使用他在指定的线程中进行数据的存储。当数据存储以后,只能在制定线程中获取到存储的数据,其余线程则没法获取到数据。
通常来讲,当某些数据是以线程为做用域而且不一样线程须要具备不一样的数据副本,这个时候就须要使用ThreadLocal。
ThreadLocal的工做原理,即是在他的set方法
public void set(T value){ Thread currentThread = Thread.currentThread();//获取当前线程 Values values = values(currentThread); if(values == null){//当前线程下的该值为空则建立一个针对该线程存在的values values = initializeValues(currentThread); } values.put(this,value); }
所以每一个值都具备了当前thread的信息,不一样thread的话会直接初始化。
get方法:
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 = initializeValues(currentThread);//此时为NULL } return (T) values.getAfterMiss(this); }
也很明显,也是包含了对线程的判断。所以如果该线程未初始化此参数,便得到的为null,并且不会产生线程不对的状况。
从ThreadLocal的set和get方法中能够看出,他们所操做的对象都是当前线程的localValues对象的table数组。所以在不一样的线程中访问同一个threadLocal的set和get方法,他们对threadLocal所作的读写操做仅限于各自线程的内部,所以能够在多个线程中互不干扰的存储和修改数据。
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 {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; }
以上为enqueueMessage的函数。此处进行的单链表的插入操做,将消息插入到了队列中。插入完成以后就须要进行读取操做。
读取操做对应的是next()
Message next() { 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 (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); } 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; } }
以上为next操做的关键部分,能够看出,当msg不为空的时候,不断进行取出,同时将原来的msg = null,所以是读取操做伴随这删除操做进行的。当全部的msg处理完毕以后,就会进入阻塞状态,等待下一个msg的到来。
looper在Android的消息机制中扮演着消息循环的角色,他会不断的从MessageQueue中查看是否有新的消息,若是有新的消息,就会当即处理,不然就会一直堵塞。
Activity建立的时候会自动建立一个looper。咱们也能够在别的线程中建立looper,只须要使用looper.prepare()这个方法。
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)); }
以上为prepare的操做,经过threadlocal来判断该线程是否已经拥有looper,打出来的异常也是一个线程只能够建立一个looper。threadlocal的set方法中同时实例了一个looper。(另有一个方法是prepareMainLooper()用于获取主线程的looper,本质也是prepare)
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
这是looper的构造函数,包含了一个实例的messageQueue和当前的线程信息。
Looper建立完毕以后,就须要进行工做了。Looper.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; 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 traceTag = me.mTraceTag; if (traceTag != 0) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } try { msg.target.dispatchMessage(msg); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } 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(); } }
Loop()的操做从源码中可知也是个死循环,惟一能够退出的msg == null的时候,而msg == null的时候,就是messageQueue的next()方法返回了null,此时是messageQueue执行了quit操做,中止了pose同时返回了null。而loop的quit操做是执行messageQueue的quit操做。所以当loop执行了quit或者messageQueue执行了quit操做时,二者都会同时被关闭。
除了quit操做以外,looper会无限制的等待messageQueue的内容。
Handler主要执行信息的发送和接受。发送经过post和send实现。
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
sendMessage执行了sendMessageDelayed,不过延时为0;
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
sendMessageDelayed又执行了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); }
sendMessageAtTime方法,实现的是messageQueue的插入操做。
所以整个send过程只是向messageQueue插入了一条信息。
Handler将信息给messageQueue,而后由looper进行处理,处理完毕以后须要通知handler来取回去继续处理。looper中进行了
try { msg.target.dispatchMessage(msg); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } }
msg.target即是handler。所以又调用了handler的回调方法dispatchMessage。
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
dipatchMessage是handler对消息的处理,handleCallback
private static void handleCallback(Message message) { message.callback.run(); }
调用了message的callback方法,这个callback是一个runnable对象,也就是此时执行runnable对象的run方法。
而msg的runnable对象不存在时,便会执行mCallback的handlemessage方法,mCallback是用于建立一个handler的实例可是不派生handler的子类。方便咱们不须要每次都新建一个handler的子类来进行重写handlemessage方法。若mCallback不存在,就直接执行handlemessage方法,也就是咱们一开始实例一个handler的时候重写的方法了。