前言
在谈Handler的时候,应该会涉及到三个角色:Handler自身、Looper、MessageQueue。这里我将一一做分析记录:
Looper
Looper类代码并不长,所以相对消化起来并不是特别的难。
Looper是一种循环机制,而且保证每个线程只能存在一个Looper机制。
讲到Looper,如果要从头开始认识这个机制,当然要参考应用的主线程main函数入口,ActivityThread。代码:
public static void main(String[] args) { ... Looper.prepareMainLooper(); ... Looper.loop(); }
再往里面看 Looper.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)); }
我们暂且不说这个prepareMainLooper有什么作用,从代码功能,我们可以看出来,程序做了两件事情:
1、sThreadLocal实例set了一个Looper的实例。
2、通过sThreadLocal.get() != null判断达到不允许该线程中重新申请一个looper实例。
其中,ThreadLocal有点像HashMap的机制,key作为一个唯一标识值,且唯一对应一个value。所以这里为当前线程实例了一个独立标识的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; //... 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) { //... } msg.recycleUnchecked(); } } ---------------------------------------------------------------------- public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
在上面的方法loop中,最有亮点当然就是for (;;)死循环了!(不然怎么叫循环机制呢哈)。从程序代码中,我们可以发现looper机制,执行循环机制的开始入口,便是loop方法!但是,我们在执行之前,应该要知道是哪个线程的Looper实例执行了?这里有个关键方法myLooper()。看到方法体的sThreadLocal.get()后,读者会不会瞬间刚刚在哪里判断的时候也调用了。
对!就是Looper机制中的prepare方法,初始化了当前Looper的实例对象,最后通过调用loop()启动了循环机制!大概我写下顺序
* 一般线程 : Looper.prepare() --> Looper.loop() * 主线程: Looper.prepareMainLooper(); ->Looper.prepare() && 初始化sMainLooper(也就是getMainLooper获取的主线程looper实例, 这个动作是synchronized线程同步的) --> Looper.loop()
MessageQueue
MessageQueue是一个消息队列机制,遵循先进先出的规则,简单讲述这里由插入与删除两个动作,其中enqueueMessag()作为消息插入、next()则是取出数据的时候程序会将其取出的数据移除消息队列,其中next是一个阻塞试的死循环机制,只要有消息插入,将进行next取出。
这里MessageQueue不做更多的说明,首先看到Looper机制是如何关联MessageQueue列的,首先定位在Looper初始化实例的构造方法与loop启动机制的方法
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
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; //... for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } ... } }
从代码结构中,可以发现消息队列MessageQueue,在构造方法中实例化。而且loop方法死循环执行中,是不断监测队列中next是否有消息来临,当然前面也说明了,next是阻塞的,因此等到有消息message插入的时候,才会通过next获取到message实例,然后在进行下一动作。
Handler
前面的铺垫就是为了今天的主角,首先分析Handler之前,我们都知道日常我们的handler用法,例如如下:
private static Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1000){ //..doing } } }; handler.sendEmptyMessage(1000);
这里我们直接通过构造方法到send方法再到接收源码进行分析
首先锁定到构造方法
public Handler(Callback callback, boolean async) { 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()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
锁定到重要的两句话mLooper = Looper.myLooper();和mQueue = mLooper.mQueue;。这里通过上面分析主线程的Looper机制,应该很熟悉了,构造器主要做的其中两个重要的事情:
1、获得当前线程(一般主线程)Looper机制实例
2、通过looper实例获得与Looper实例绑定关系的消息队列实例mQueue
其次我们再看下发送消息,这里我直接跳转到最终处理消息的逻辑:
sendEmptyMessage ->sendEmptyMessageDelayed ->sendMessageDelayed ->sendMessageAtTime->enqueueMessage
发送个消息也不容易啊~
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); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
不知道读者注意到了没有,最终Handler发送Meesage的时候,其实最终还是调用了与当前线程的Looper实例所绑定的消息队列中的enqueueMessage,即只是一个插入message到消息队列的过渡者!当然,其中通过msg.target = this;,message对象绑定了调用目标是当前Handler对象。这里我建议读者可以手动自己看下源码,不难理解。
前面简述MessageQueue的时候有提及到,MessageQueue只有两个操作,即单链表的插入以及删除。由于next()是阻塞式的死循环,只要消息队列有消息,则马上将message取出并溢出。
最后联系到真正处理转发的Looper实例,前面也说loop方法死循环执行中,在不断监测队列中next是否有消息来临。如果Handler此时发送Message到消息队列中,则绑定关系中的Looper实例中的loop方法将会获得此时的message,经过消息队列终于来到当前线程的looper机制中,此时loop方法通过msg.target.dispatchMessage(msg)返回给Hander对象,这里我再贴下loop方法
public static void loop() { ... for (;;) { Message msg = queue.next(); // might block if (msg == null) { return; } // 这里的target,前面我们可以在Handler看到每个Message都会通过target绑定发送Handler对象 // 最终消息交给Handler中dispatchMessage方法处理 msg.target.dispatchMessage(msg); msg.recycleUnchecked(); } }
// 最终处理再转发给 handleCallback 或 handleMessage public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
上面笔者直接通过注释讲述了最后的处理。当然这里我们也可以观察下这里面的mCallback,这里是我们初始化Handler的时候有构造方法可以将mCallback进行初始化,这里我们可以观察到在执行Handler的handleMessage前还经过mCallback.handleMessage(msg)的判断,说明mCallback在这里起到一个拦截的作用,如果实例者回调返回true,就不会将消息回调给handleMessage。
笔者是花了三个多小时过了下源码和记录了分析的笔记,当别人提起底层的源码机制,这块真的有点薄弱。平常应用层开发多了,花在源码层分析的时间也少了,所以一有时间还是得多读读书,多读读代码,提升下思维和能力~共勉哈!最后我引用下别人的一张图做最后的总结,感谢阅读!
Android Handler.png
傻小孩b mark共勉,写给在成长路上奋斗的你