老司机们都知道,Android的线程间通信就靠Handler、Looper、Message、MessageQueue这四个麻瓜兄弟了,那么,他们是怎么运作的呢?下面做一个基于主要源代码的大学生水平的分析。 原文链接
Looper在 Looper 中,维持一个Thread
对象以及MessageQueue
,通过Looper的构造函数我们可以知道:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//传入的参数代表这个Queue是否能够被退出
mThread = Thread.currentThread();
}
Looper
在构造函数里干了两件事情:
- 将线程对象指向了创建
Looper
的线程 - 创建了一个新的
MessageQueue
分析完构造函数之后,接下来我们主要分析两个方法:
looper.loop()
looper.prepare()
public static void loop() {
final Looper me = myLooper();//获得当前线程绑定的Looper
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//获得与Looper绑定的MessageQueue
// 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();
//进入死循环,不断地去取对象,分发对象到Handler中消费
for (;;) {
Message msg = queue.next(); // 不断的取下一个Message对象,在这里可能会造成堵塞。
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);
}
//在这里,开始分发Message了
//至于这个target是神马?什么时候被赋值的?
//我们一会分析Handler的时候就会讲到
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?