Handler源码剖析
2017-07-23 14:25
483 查看
在分析handler之前,先要搞明白Handler是什么? Handler涉及到那些关键类?这些关键类主要作用是什么?他们是如何工作的?这些问题搞懂了之后,handler的机制就基本上全明白了。
Handler:进程中用来线程通讯的过程。
Handler涉及的关键类有那些?
既然是通讯,那必然就要通讯内容的载体Message。
Message就要有一个消息仓库,MessageQueue。
有了消息队列了,那必然有一个取消息的Looper
那么看看这些类是如果工作的,看一副简易的手绘图。
![](https://img-blog.csdn.net/20170723131313619?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvWkFDSF9aSE9V/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
图片很简单,但是handler的大体流程已经很清除了,首先handler通过sendMessage()方法,将Message加入了MessageQueue,然后Looper通过loop又将消息返回给了handler,最后是由handler进行处理消息的,也就是我们熟悉的handleMessage()方法。大体流程了解之后,开始我们的源码分析,看看是不是这样的。
源码分析:
进入Handler的sendMessage()方法
sendMessage最后返回值是调用了sendMessageDelayed(msg,0)这个方法,延时默认是0,跟进。
sendMessageDelayed最后返回值是调用了sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)这个方法,跟进。
最后这个方法调用了enqueueMessage(queue, msg, uptimeMillis),注意第一个参数 MessageQueue queue = mQueue; 这里给MessageQueue赋值了,这个mQueue是在那里赋值的呢?我们先不管他,继续跟进
然后调用了queue.enqueueMessage(msg, uptimeMillis);这个queue就是mQueue,这里给msg.target赋值了当前的Handler对象,最后看一下queue.enqueueMessage(msg, uptimeMillis),
最后跟进
这个方法很长,并且有native方法,不去深究太多,直接看一段注释即可,
这个方法就是是将消息插入消息队列。并且告知消息队列中已经存在消息,可以在消息队列中获取消息。到此为止,sendMessage将消息加入了消息队列。现在可以看一下mQueue是在那里赋值的。
mQueue = mLooper.mQueue; 这个消息队列是looper中的消息队列。
消息队列中有了消息,那么Looper就可以循环消息队列中的消息了,进入loop()方法
在Looper中调用了Message msg = queue.next(); 来获取消息,queue.next获取的也就是消息队列中的消息了,获取到消息之后msg.target.dispatchMessage(msg);调用了这个方法,这个msg.target就是Message指定的Handle,是不是很巧妙啊。然后调用了handler的dispatchMessage(msg)方法,最终又调用了handler的handleMessage(msg)方法了。
最后还有一个问题,主线程中存在一个Looper,那这个Looper是何时初始化的呢?继续看ActivityThread中的main()
找到Looper.prepareMainLooper();了,原来这个是在主线程的main方法中初始化的,也就是说,当app运行的时候就自带了Looper和MessageQueue。
好,到这里,源码分析的就差不多了,最后说一下MessageQueue吧,内部其实是采用了生产者和消费者模式,有兴趣的伙计可以研究研究院,多做交流
Handler:进程中用来线程通讯的过程。
Handler涉及的关键类有那些?
既然是通讯,那必然就要通讯内容的载体Message。
Message就要有一个消息仓库,MessageQueue。
有了消息队列了,那必然有一个取消息的Looper
那么看看这些类是如果工作的,看一副简易的手绘图。
图片很简单,但是handler的大体流程已经很清除了,首先handler通过sendMessage()方法,将Message加入了MessageQueue,然后Looper通过loop又将消息返回给了handler,最后是由handler进行处理消息的,也就是我们熟悉的handleMessage()方法。大体流程了解之后,开始我们的源码分析,看看是不是这样的。
源码分析:
进入Handler的sendMessage()方法
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
sendMessage最后返回值是调用了sendMessageDelayed(msg,0)这个方法,延时默认是0,跟进。
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
sendMessageDelayed最后返回值是调用了sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)这个方法,跟进。
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); }
最后这个方法调用了enqueueMessage(queue, msg, uptimeMillis),注意第一个参数 MessageQueue queue = mQueue; 这里给MessageQueue赋值了,这个mQueue是在那里赋值的呢?我们先不管他,继续跟进
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就是mQueue,这里给msg.target赋值了当前的Handler对象,最后看一下queue.enqueueMessage(msg, uptimeMillis),
最后跟进
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; }
这个方法很长,并且有native方法,不去深究太多,直接看一段注释即可,
// 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.
这个方法就是是将消息插入消息队列。并且告知消息队列中已经存在消息,可以在消息队列中获取消息。到此为止,sendMessage将消息加入了消息队列。现在可以看一下mQueue是在那里赋值的。
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; }
mQueue = mLooper.mQueue; 这个消息队列是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; // 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 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) { 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中调用了Message msg = queue.next(); 来获取消息,queue.next获取的也就是消息队列中的消息了,获取到消息之后msg.target.dispatchMessage(msg);调用了这个方法,这个msg.target就是Message指定的Handle,是不是很巧妙啊。然后调用了handler的dispatchMessage(msg)方法,最终又调用了handler的handleMessage(msg)方法了。
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
最后还有一个问题,主线程中存在一个Looper,那这个Looper是何时初始化的呢?继续看ActivityThread中的main()
public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); 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()); AndroidKeyStoreProvider.install(); // 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")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); } }
找到Looper.prepareMainLooper();了,原来这个是在主线程的main方法中初始化的,也就是说,当app运行的时候就自带了Looper和MessageQueue。
好,到这里,源码分析的就差不多了,最后说一下MessageQueue吧,内部其实是采用了生产者和消费者模式,有兴趣的伙计可以研究研究院,多做交流
相关文章推荐
- Discuz!NT控件剖析 之 DataGrid(数据列表) [原创: 附源码]
- C语言编译全过程剖析
- Android开源项目SlidingMenu深入剖析
- C编译器剖析PDF文档及UCC编译器162.3
- NGUI内核大剖析(一) UIRect
- UML类图关系全面剖析
- iPhone/Mac Objective-C内存管理教程和原理剖析(四)系统自动创建新的autorelease pool
- C编译器剖析_C类型系统_相容类型Compatible Type
- 以蓝牙为背景剖析无线通信原理以及协议栈
- ExecutorService与Executors例子的简单剖析
- 专访网络安全专家傅盛:剖析木马犯罪产业链
- [学习笔记]C语言深度剖析
- HTML语言剖析
- 智能指针之auto_ptr源码剖析
- webservice中的wsdl文件的剖析,已经swebservice客户端调用的几种方式
- 全面剖析C#接口编程之实现接口 (2)
- TCP拥塞控制算法内核实现剖析(五)
- UIView的剖析!
- oracle学习笔记 Oracle日志原理剖析
- go-ethereum源码剖析:交易