Android消息机制Handler源码简单解析
2016-11-23 14:31
579 查看
一,概述
这几天一直在看《Android开发艺术探索》,对于我这个Android还没有学多久的人,说实话难度还是有大。其中Android消息机制这一章,看了半天,总算流程大致走了一遍,虽说不是都弄明白了,但是感觉收获还是不小。首先借用别人的一张Handler消息机制流程图(http://www.jianshu.com/p/c3459c13deff)Android消息机制主要就是指Handler运行机制,所附带的MessageQueue和Looper的工作过程,接下来将从这三方面一一介绍。
二,Handler
相信在做开发时,Handler经常会被使用,他是Android消息机制的上层接口,打交道的机会自然不会少。它的使用过程就是将一个任务切换到Handler所在线程中去,而刚开始很多初学者,都会认为Handler只能在主线程中创建,然后在子线程中执行耗时任务,发送消息通知Handler更新UI。其实不然,首先看Handler的构造方法,Handler的构造方法有多种重载,通常我们在主线程中构建的Handler通常会跳到这个构造方法public Handler(Callback callback, boolean async) { 。。。 mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } 。。。。 }
在这个构造方法中我们可以看见如果mLooper为null,就会抛出Can’t create handler inside thread that has not called Looper.prepare()异常。从这里我们就可以得出一个结论如果一个线程中Looper为null,就会报错。那为什么主线程可以直接实例化Handler?来来,容贫道一一道来,首先看ActivityThread的main方法,
public static void main(String[] args) { 。。。。 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")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
是不是很熟悉main方法,这不是我们学java天天写的主函数吗?好吧,它就是主线程的入口函数,接下来可以看到Looper.prepareMainLooper(),打开prepareMainLooper()方法我们看见如下:
public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } 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)); }
上面两个方法主要就做了两件事:
1 .实例化了一个Looper,注入给sThreadLocal
2 .myLooper()赋给sMainLooper
至于ThreadLocal以后再说,暂且不讨论,大家可以将它理解为一个数据存储类,且每个线程只有一个存储变量副本。loop()后面在介绍Looper()再介绍
从上面可知主线程在初始化时就实例化了Looper,所以,主线程中可以直接实例化Handler()。从上面可以知道,如果我们想实例化Handler,就必须先有Looper,故,Handler在子线程中也可以创建。那么我们该如何在子线程中创建Handler了,下面给出例子:
new Thread(){ @Override public void run() { //为当前线程创建一个Looper Looper.prepare(); handler = new Handler(){ @Override public void handleMessage(Message msg) { } }; handler.sendEmptyMessageDelayed(0, 1000); //开启消息循环 Looper.loop(); } }.start();
好了,构造方法讲完了,接下来就是消息的发送,我们一般可以通过两种方法发送消息。
1.send….. 一般在handMessage中处理消息
2.post….. 一般在runable中处理消息
post….底层也是调用send…..发送消息,典型执行过程如下
//1. public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } //2. public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } //3. 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); } //4. private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
可以看到消息最终通过enqueueMessage投递到消息队列queue,其中msg.target = this就是指的消息处理者自己,后面Looper中会使用,这里先介绍下。
三,MessageQueue
MessageQueue的中文翻译就是消息队列,顾名思义,它的内部提供了一组消息,以队列的形式对外提供插入和删除操作。虽然叫消息队列,但它的内部是通过单链表的形式提供插入和删除操作。这里插入和删除是enqueueMessag和next,其中enqueueMessag往消息队列底部插入一条消息,next()则是取出消息,并将取出的消息移除回收掉,且next是一个阻塞试的死循环机制,只要有消息插入,将进行next取出。下面大概看下源代码boolean enqueueMessage(Message msg, long when) { 。。。 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; } }
这段代码可以看出, 它是一个无限循环的消息,会无限的检测是否有消息。当有消息到来时,next会取出消息,并从队列里面取出。
四,Looper
首先看下其构造方法private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在构造方法中实例化了MessageQueue。通常MessageQueue只负责消息的插入和读取,不负责消息的处理,而Looper是一个无限的消息循环,它负责从消息队列中取出消息并发给Handler处理,看下刚刚没有介绍的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); } } ...... }
可以看出它是一个无限的消息循环,Message msg = queue.next()程序会阻塞在这里,如果没有消息到来,当looper检测到消息时会取出msg,然后执行msg.target.dispatchMessage(msg); 刚刚我们说到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); } }
它的执行过程可以用张图概述下:
(稍微有点丑,将就下)
可以看出,平常我们直接实例化Handler(),就只会调用最后的handleMessage(msg),在handler中handleMessage是一个空实现,需要我们在调用时手动实现。而另外一个CallBack是一个内部接口,它的实现如下
/** * Callback interface you can use when instantiating a Handler to avoid * having to implement your own subclass of Handler. * * @param msg A {@link android.os.Message Message} object * @return True if no further handling is desired */ public interface Callback { public boolean handleMessage(Message msg); }
那么它的意义是什么? 从接口上面注释就可以看见,它的实现是为了不需要去派生Handler的子类,日常生活中通常是直接实例化Handler,并重写handleMessage,但是有时候,可以这样写
private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { return false; } });
返回值就是一个Boolean型变量,从那个图我们可以看见返回true就是自己消费了,handler的handleMessage不需要处理,false,就是要调用系统的handleMessage处理,这就是它的执行过程。
总结
好了,到了这里,它的基本过程以及涉及的三个部分Handler,MessageQueue,Looper都介绍了一遍,稍微再总结下吧1 .Handler负责在子线程中发消息,消息会到MessageQueue底部。
2 .MessageQueue负责将消息加到队列,以及取出消息并回收掉。
3 .Looper负责检测MessageQueue是否有新消息,如果有就取出消息,然后发给消息发送者处理,此时线程已经从子线程切换到了另一个线程(通常是主线程)。
整个过程大致就是这,看到结果还是蛮容易理解的,不过内部执行过程确实很复杂(发个消息也不容易啊)! 好了,就到这里了!!!!!
相关文章推荐
- android的消息处理惩罚机制(图+源码解析)——Looper,Handler,Message
- Handler Looper源码解析(Android消息传递机制)
- Android消息机制源码解析(二)——消息的执行者Handler
- Android消息机制Handler解析(源码+Demo)
- Android HandlerThread 消息循环机制之源码解析
- [Android] 异步消息处理机制(Handler 、 Looper 、MessageQueue)源码解析
- [Android] 异步消息处理机制(Handler 、 Looper 、MessageQueue)源码解析
- Android多线程消息处理机制(四) Message、MessageQueue源码解析和Handler综合使用
- Android Handler 异步消息处理机制二:源码解析,深入理解Looper、Handler、Message三者关系
- Android 异步消息处理机制(Handler 、 Looper 、MessageQueue)源码解析
- Android 消息机制:Handler、Looper、Message源码 详细版解析 ------从入门到升天
- 【 Android】handler异步消息处理机制完全解析,带你从源码的角度彻底理解
- Android 异步消息处理机制(Handler 、 Looper 、MessageQueue)源码解析
- Android消息机制Handler,MessageQueue,Looper源码解析
- Android Handler消息机制源码解析(上)
- Android Handler消息机制源码解析(下)
- 带你从源码看Android Handler 异步消息处理机制完全解析
- Android 异步消息处理机制(Handler 、 Looper 、MessageQueue)源码解析
- Android源码解析Handler系列第(三)篇---深入了解Android的消息机制
- 从源码来一步一步解析Android中Handler消息机制