handler源码分析
来源:互联网 发布:python宝典 编辑:程序博客网 时间:2024/06/03 21:47
handler类里面有个dispatchMessage()方法,是handler处理消息的方法
/** * Handle system messages here. */ public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
消息拦截的顺序msg.callback->handler构造的传进来的mCallback->调用handler成员方法handlerMessage(msg)
Message的callback
/** * Same as {@link #obtain(Handler)}, but assigns a callback Runnable on * the Message that is returned. * @param h Handler to assign to the returned Message object's <em>target</em> member. * @param callback Runnable that will execute when the message is handled. * @return A Message object from the global pool. */ public static Message obtain(Handler h, Runnable callback) { Message m = obtain(); m.target = h; m.callback = callback; return m; }
这个message的callback就是一个Runnable
再看handler的成员mCallback
* * @param callback The callback interface in which to handle messages, or null. */ public Handler(Callback callback) { this(callback, false); }
所以为什么创建handler时候如果传递一个callBack,重写的handleMessage方法就无效的原因
handler类的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); }
再看参数最多的这个构造方法
* @param looper The looper, must not be null. * @param callback The callback interface in which to handle messages, or null. * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for * each {@link Message} that is sent to it or {@link Runnable} that is posted to it. * * @hide */ public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
可以看到looper是必须要传进去的,那我们平时用的handler在主线程序创建为什么没有传进去looper呢,找到其他构造方法
* @param callback The callback interface in which to handle messages, or null. * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for * each {@link Message} that is sent to it or {@link Runnable} that is posted to it. * * @hide */ 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; }
看到我们主线程创建handler的时候其实会去调用mLooper = Looper.myLooper();来获取一个looper对象
/** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
ThreadLocal其实就是一个全局的Map对象,保存的key就是当前线程对象,value就是looper对象,这样在哪个线程调用就取得是哪个线程对应的looper,那么在这个地方调用是要从主线程获取looper了
// sThreadLocal.get() will return null unless you've called prepare(). static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); private static Looper sMainLooper; // guarded by Looper.class
可以看到这个主线程的sMainLooper 是静态的成员变量,也就是说每个aplication的生命周期内会创建且存在一个looper对象
那么什么时候创建的呢,在Looper对象类中找不到,其实Activity在被创建的时候,框架会帮我们初始化一个Looper对象,因此在主线程中,我们不必去调用Looper.prepare()去初始化Looper对象。
我们经常调用的post(runnable)就能实现任务调度处理,又是怎么实现的呢
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
–>
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
其实还是创建了一个Message对象等到处理消息导读的时候在message的callback回调
继续跟进
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
在跟进
* occurs then the message will be dropped. */ 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); }
如果消息队列对象不存在,打印异常,返回false
再跟进
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
queue.enqueueMessage(msg, uptimeMillis)就是把消息对象添加到queue里面,并且重点是msg的target绑定是当前handler对象,等looper轮训到这个msg的时候就可以拿出来msg的target对象并且调用他的处理方法,继续跟进到messageQueue类中
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; }
—-1>
if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); }
添加进来的msg必须要有对应的handler对象,否则抛出异常
—-2>
Message p = mMessages;
mMessages代表当前队列(实际就是一个链表,接下来我用链表代替),如果p==null证明这个链表是空的,需要初始化链表操作
—-3>
if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked;
那么此时的msg就是链表的head,因为此时只有一个所以msg.next指向p,也就是null
—-4>
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;
用一个prev指向链表最后一个节点,然后让p=p.next(即null),p==null;break
msg.next指向p,让prev即链表的最后一个元素的next指向msg,就完成了链表添加
那么此时就完成了handler的创建,发送message到添加到messageQueue中等待Looper去轮询
那么很明了,我们创建一个handler(消息发送处理器),对应必须要有一个(looper消息轮询器)和一个MessageQueue(消息队列|消息链表),如何说明对应一个MessageQueue呢
handler中
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;
跟进到looper中
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
真相明了,每创建一个looper对象就会创建一个queue,至于lopper的轮询放在下一篇
queue的轮询任务是looper的loop()方法实现的
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the 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(); } }
一个while true循环不停的进行轮询
之前有人问我当消息队列为空时,还进行轮询么
for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; }
取出来一个msg,当没有消息的时候msg==null,这时候return就跳出轮询,所以答案是否
try { msg.target.dispatchMessage(msg); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } }
拿到msg的target就是handler对象,调用dispatchMessage(msg)方法
就来到了最开始我们分析的handler处理消息的方法
- Handler 源码分析
- Handler的源码分析
- Looper、Handler源码分析
- Handler源码分析
- [Android源码]Handler分析
- handler 源码分析
- Android Handler源码分析
- Android Handler源码分析
- Handler源码分析
- Handler源码分析
- Handler的源码分析
- Handler机制.源码分析
- Handler源码分析
- Handler 机制 源码分析
- Handler运行机制源码分析
- Handler源码分析
- Handler源码分析
- 源码分析Handler机制
- c 字符串处理函数,字符串类和字符串变量
- 两点距离
- Tensorflow 保存和加载模型
- PHP中MySQL的连接封装
- 2017图灵杯问题E 简单的RMQ(RMQ)
- handler源码分析
- 到底什么时候该使用MQ?(MQ使用场景分析)
- 【python 下载器】python下载电影&视频&电视剧
- 我的博客开端
- Hbase架构与原理
- 一种摄像机跟随方式
- java UTF-8转GBK怎么转?
- EL
- GCD 和 NSOperation的区别