引入:
提到Android中的消息机制,大家应该都不陌生,我们在开发中不可避免的要和它打交道。从我们开发的角度来看,Handler是Android消息机制的上层接口。我们在平时的开发中只需要和Handler交互即可。通过Handler我们可以将一个任务切换到Handler所在的线程中执行。日常中我们使用Handler的场景可能大多是在子线程中进行了耗时操作,比如网络请求数据,拿到数据后我们可能会更新UI控件,因为Android规定只能在主线程进行UI操作,这时候我们通常会在主线程中创建一个Handler,然后通过在子线程中使用Handler发送消息发送到主线程,然后在主线程中消息回调的handleMessage()中处理我们的消息。但是本质来说,Handler并不是专门用来更新UI的,这是它的一个用途而已。
为什么需要这样的一个消息机制呢?
我们知道每一个应用程序都有一个主线程,如果我们直接与主线程交互,访问他的一些变量,对其进行一些修改操作,可能会带来线程安全问题,并且不利于Android系统的整体运作。通过Android系统提供的一条消息处理机制,我们通过在子线程发送消息形式,让主线程进行处理,然后我们的逻辑代码就可以执行了。
具体的消息有两种:我们自己定义的Handler和系统的Hander,其实我们Android中四大组件的运作也都是系统Handler进行着消息的处理,从而实现各个生命周期的回调,当然这里的消息种类很多,就不一一列举了。这里注意一点,我们应用退出程序得到过程,应用程序退出应用其实就是让主线程结束,换句话说也就是让我们这里的Looper循环结束,这样我们的四大组件生命周期就不会执行了,应为四大组件生命周期的回调依赖于Handler处理,Looper循环都没了,四大组件还玩毛线哦。所以有时候我们的onDestroy方法不一定会回调。
Android消息机制概述:
Android的消息机制其实主要是指Handler的运行机制,而Handler的运行又需要底层MessageQueue和Looper的支撑。MessageQueue中文翻译是指消息队列,顾名思义,它的内部存储了一组消息,以队列的形式对外提供插入和删除的工作。虽然叫消息队列,但是它的内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表。这也可以想到,因为链表的结构对于插入删除操作执行的效率比较高。Looper中文翻译为循环,由于MessageQueue只是提供了一个消息的存储,它并不能去处理消息,Looper就填补了这个功能,Looper会以无限循环的方式去查找是否有新消息,如果有的话就处理否则就会一直等待着。
其次Looper中还要一个特殊的概念ThreadLocal,用它可以在不同的线程中存储数据,互不干扰。Handler创建的时候使用当前的Looper来构造消息循环系统,那么在Handler如何获取到当前线程的Looper呢。就是通过这个ThreadLocal,ThreadLocal可以在不同线程中互不干扰的存储和读取数据,通过ThreadLocal就可以轻松获取到每个线程的Looper。需要注意的是线程默认是没有Looper的,我们在子线程使用Handler必须先创建Looper否则会发生异常。至于主线程为什么可以直接使用Handler呢?那是因为主线程在入口的main方法中就已经帮我们创建了一个Looper对象,并开启了一个Looper循环,帮我构建好了这样一个消息消息循环的环境。这里了解一下Android规定访问UI只能在主线程中进行,如果在子线程中访问UI就会发生异常,这是因为ViewRootImpl对UI的操作做了验证,这个验证是在ViewRootImpl的checkThread()方法中完成的。
void checkThread() { if (mThread != Thread.currentThread()) { throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }
因此由于这个的限制对AndroidUI的操作必须在主线程,但是Android又不建议在主线程中执行耗时的操作,因为会阻塞主线程导致ANR异常。因此Handler就应运而生了,系统提供Handler主要原因是解决在子线程中无法更新UI的矛盾。那么刚才提到为什么不允许子线程中访问UI呢?那是因为Android的UI控件并不是线程安全的。如果存在多线程的并发访问可能会导致UI控件处于不可预期的状态。那么系统为什么不对UI控件加锁呢。一方面加锁使逻辑更复杂,二来要进行锁判断,影响效率,阻塞了其它线程,所以简单高效的模型就是单线程。对于我们来说也不麻烦一个Handler就哦了。
消息队列MessageQueue的工作原理:
MessageQueue主要包含两个操作:插入和读取。读取本身伴随着删除操作,对应着两个方法分别是enqueueMessage()和next()。enqueueMessage是插入一条消息到消息队列中,next是取出一条信息并将其从队列移除。看他的方法源码可以看到enqueueMessage主要是进行单链表的插入操作。next是一个无线循环,如果么有消息,next会一直阻塞在这里,如果有消息到来,next会返回这个消息并将其从队列移除。
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; }
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; } }
Looper的工作原理:
Looper会不停的从MessageQueue中查看是否有新消息,有的话立刻处理,没有就会一直阻塞,它的构造函数初始化了一个MessageQueue,并获取到当前线程。
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
Handler的运行需要Looper的支持,那么怎么创建Looper呢,可以调用Looper.prepare()方法,
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.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 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); } // 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(); } }
Looper还提供了一个getMainLooper()这个是用来便捷的获取主线程的Looper的。Looper也是可以退出的,他提供了quit和quitSafely方法来退出Looper,quit是直接退出Looper,而quitSafely会先处理完毕消息队列的消息再退出。
public void quit() { mQueue.quit(false); } public void quitSafely() { mQueue.quit(true); }
Looper退出后,通过Handler发送的消息会失败,如果在子线程中创建Looper我们应该在不需要的时候终止Looper。Looper的loop方法工作流程:loop方法是一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回null。当Looper执行quit方法时,会调用MessageQueue的quit或者quitSafely来通知消息队列的退出,当队列被标记退出状态时,它的next会返回null.通过MessageQueue.next来获取新消息,否则会一直阻塞,MessageQueue的next返回新消息,Looper就会处理这条消息调用msg.target.dispatchMessage()方法。其实这个target就是Message持有的Handler引用。所以最终是交给Handler调用dispatchMessage()来处理这个消息。因为dispatchMessage是在创建Handler时所使用Looper中执行的,这样就把代码逻辑切换到了指定线程中执行了。
Handler的工作原理:
其实Handler的工作就是消息的发送和接收,发送消息可以通过一系列的post方法和send方法,而post方法最终也是通过send来发送的。那么最终都是走下面这个方法。
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); }
Handler发送消息的过程就是仅仅是向消息队列中插入了一条消息,MessageQueue的next方法返回了这个消息交给Looper,Looper接收到消息就开始处理了。最终的消息是交由Handler处理,即Handler的disaptchMessage会被调用,这时候Handler就进入了消息处理的过程,Handler处理消息的过程如
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
首先检查Message的callBack是否为空,不为空就通过handleCallback来处理消息,Message的CallBack就是一个Runnable对象,实际上就是通过post方法传递的Runnable参数,其次是检查mCallBack是否为null,不为空就调用mCallBack的handleMessage()方法,通过CallBack我们可以如下创建Handler。 Handler handler=new Handler(callback).这里不需要派生一个子类对象,在日常中我们就是创建Handler子类对象,并重写handleMesaage方法。不过注意callback的handleMessage方法的返回值boolean会影响到Handler自己的handleMessage的调用,用到的时候要注意。
程序的入口分析
public static void main(String[] args) { SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); // Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter()); Security.addProvider(new AndroidKeyStoreProvider()); // 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(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
这是Android应用程序启动的入口main方法。注意到这里面比较关键的几行代码
- Looper.prepareMainLooper();点进方法里可以看到在该方发中首先从ThreadLocal中获取到looper对象,如果存在则抛出异常(只能创建一次),然后new Looper()创建一个Looper对象并与当前的线程绑定,具体的绑定方式请随我看。首先获取到当前所在的线程,然后通过该线程对象获取到该线程的 ThreadLocalMap集合,然后以当前线程对象做为key,所创建的Looper对象作为value进行map结合的存储。这样Looper与线程之间通过ThreadLocal就进行绑定了起来。
sThreadLocal.set(new Looper(quitAllowed)); public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
- ActivityThread thread = new ActivityThread();这句话创建了ActivityThread对象, 大家如果看源码的话可以看到该类定义了一个H mH的成员变量,没错这个mH就是系统的Handler,很特别,该变量在定义的时候就进行了初始化,这行代码走完之后,mH就相应的有值了。
- Looper.loop();这个方法就比较牛了,可以说我们应用程序的运行就依赖于它,点进该方法可以看到,它里面是一个for死循环。不断的进行消息的获取处理,从而使我们程序一直运行下去。
补充说明消息机制中涉及的几个要素
- Looper:Looper其实是充当着一个循环器的作用,它的内部持有MesageQueue、Thread、和ThreadLocal(其内部的map集合用于存储Looper和线程,实现两者的绑定)其中prepare()方法用于创建Looper对象并进行存储(存储方式前面说过),loope方法即是一个消息处理的循环器。,不断的从MessageQueue中取出消息交由Handler处理。
- Message消息对象,它的内部有持有Handler和Runnable的引用以及消息类型。其中有一个比较重要的方法obtain(),取消息,该方法的内部是先通过消息池来获取池中的消息,没有则创建,实现了Message对象的复用。其内部有一个target引用,该引用是一个Handler对象的引用,在Looper中提到的消息处理就是通过Message持中的target引用来调用Handler的dispatchMessage()方法来实现消息的处理。还有这个Runnable引用。这个引用会在消息的处理中看到,在dispatchMessage()方法中会先判断这个Message得callBack是否为空,如果不为空则走handleCallBack方法最终将走到Runnable的run方法
这个我们经常遇到,比如我们通过Handler.post().....等一系列post方法,该方法实现消息发送的原理就是将线程任务Runnable封装到消息对象Message中,最终会走到这个Runnable的run方法中执行,所以这个过程中并没有开启一个线程,仍然是在主线程中运行的。因此不要有耗时的操作,否则会阻塞主线程。
- MessageQueue:消息队列,其实不应该这样称呼,应为他的结构并不是一个队列,而是一个链表(这样说方便理解)它实现了对消息Message的存储,以及消息在链表中的排列以取出消息的顺序。
- Handler:Handler主要是扮演者消息发送和消息处理的角色,这里我将对他的一些方法进行介绍:
(1)构造方法:Handler有一系列的构造方法,这个自行查阅,他也可以有自己的回调处理CallBack,在消息处理dispatchMessage中我们可以看到有这样一个判断,如果mCallback!=null会执行它自己的handleMessage方法,该方法的返回值直接决定了下面handleMessage的执行与否。
(2)一系列的Post()方法(原理上面说过啦)其实最终都是将任务进行了消息的封装插入到MessageQueue中,最终Runnable不为空,处理消息时会回调自己的run()方法。
(3)sendMessage()....等方法也是对消息就行了封装最后插入到了消息对列中
(4)removeCallbacks(Runnabler)改方法是对通过post发送方式进行消息的清除,还有removeMessage(int what)通过消息类型进行移除,还removeAllbacksAndAMessages()将会移除所有的callbacks和messages
总结
在主程序的入口main方法中进行了主线程Looper的创建以及Handler的创建,以及将改Looper与主线程绑定。然后通过Looper.loop方法进行消息的循环,不断的从消息队列(在初始化Looper的构造函数中进行了MessageQueue的初始化)取出消息,然后交给Message所持有的Handler来处理,Handler通过调用dispatchMessage()方法来处理消息。从而形成了整个消息系统机制。注意:因为我们一般使用Handler都是在主线程中,不用考虑Looper的创建,因为刚才说了,启动程序时候默认给我们创建了一个Looper对象,所在在这个环境下我们可以自由使用Handler,但是如果我们要在子线程中使用Handler就必须先通过Looper.prepare()方法创建一个Looper对象,然后创建handler对象然后通过Looper.loop()方法实Loop循环,不断的处理消息。