Looper、MessageQueue、Message、Handler的关系
1.快速复习
1.1 基本装置
| 类 | 装置名 | 作用 | 线程中数量 |
| Looper | 消息分发装置 | 从消息队列中取出一个消息,交给对应的Handler处理消息。 | 1 |
| MessageQueue | 消息队列 | 保存所有消息 | 1 |
| Message | 消息 | 封装通信数据 | n |
| Handler | 消息的发送和处理装置 | 处理消息,发送消息。 | n |
每个想通信的线程都要安装上述装置,主线程默认已经安装。
1.2 基本工作流程
Looper.prepare();
Looper.loop();
...
Hanlder.sendMessage(xxx);
Hanlder.handleMessage(xxx);
Looper.quit();
1.3 安装后两个线程间如何通信?
线程B得到线程A中的hanlder5(一个线程中可有多个hanlder)后,就可用它向线程A发送消息,然后分发装置将该消息交给hanlder5处理。
2.Looper
先分析这个是因为能够引出四者的关系.
2.1 MessageQueue
在Looper中,维持一个Thread对象以及MessageQueue,通过Looper的构造函数我们可以知道:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//传入的参数代表这个Queue是否能够被退出
mThread = Thread.currentThread();
}
Looper在构造函数里干了两件事情:
- 将线程对象指向了创建
Looper的线程 - 创建了一个新的
MessageQueue
分析完构造函数之后,接下来我们主要分析两个方法:
looper.loop()looper.prepare()
2.2 looper.loop()
在当前线程启动一个Message loop机制,此段代码将直接分析出Looper、Handler、Message、MessageQueue的关系.
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("<<<<< 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);
}
//当分发完Message之后,当然要标记将该Message标记为 *正在使用* 啦
msg.recycleUnchecked();
}
}
分析了上面的源代码,我们可以意识到,最重要的方法是:
queue.next()msg.target.dispatchMessage(msg)msg.recycleUnchecked()
其实Looper中最重要的部分都是由Message、MessageQueue组成的有木有!这段最重要的代码中涉及到了四个对象,他们与彼此的关系如下:
MessageQueue:装食物的容器Message:被装的食物Handler(msg.target实际上就是Handler):食物的消费者Looper:负责分发食物的人
2.3 looper.prepare()
在当前线程关联一个Looper对象
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//在当前线程绑定一个Looper
sThreadLocal.set(new Looper(quitAllowed));
}
以上代码只做了两件事情: 1. 判断当前线程有木有Looper,如果有则抛出异常(在这里我们就可以知道,Android规定一个线程只能够拥有一个与自己关联的Looper)。 2. 如果没有的话,那么就设置一个新的Looper到当前线程。
3.Handler
由于我们使用Handler的通常性的第一步是:
Handler handler = new Handler(){
//你们有没有很好奇这个方法是在哪里被回调的?
//我也是!所以接下来会分析到哟!
@Override
public void handleMessage(Message msg) {
//Handler your Message
}
};
所以我们先来分析Handler的构造方法
//空参数的构造方法与之对应,这里只给出主要的代码,具体大家可以到源码中查看
public Handler(Callback callback, boolean async) {
//打印内存泄露提醒log
.... //获取与创建Handler线程绑定的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获取与Looper绑定的MessageQueue
//因为一个Looper就只有一个MessageQueue,也就是与当前线程绑定的MessageQueue
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async; }
4.问题
Looper.loop()死循环中的msg.target是什么时候被赋值的?handler.handleMessage(msg)在什么时候被回调的?
4.1 Looper.loop()死循环中的msg.target是什么时候被赋值的?
要分析这个问题,很自然的我们想到从发送消息开始,无论是handler.sendMessage(msg)还是handler.sendEmptyMessage(what),我们最终都可以追溯到以下方法
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//引用Handler中的MessageQueue
//这个MessageQueue就是创建Looper时被创建的MessageQueue
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
//将新来的Message加入到MessageQueue中
return enqueueMessage(queue, msg, uptimeMillis);
}
接下来分析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);
}
4.2 handler.handleMessage(msg)在什么时候被回调的?
通过以上的分析,我们很明确的知道Message中的target是在什么时候被赋值的了,我们先来分析在Looper.loop()中出现过的过的dispatchMessage(msg)方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//看到这个大写加粗的方法调用没!
**handleMessage(msg);**
}
}
加上以上分析,我们将之前分析结果串起来,就可以知道了某些东西: Looper.loop()不断地获取MessageQueue中的Message,然后调用与Message绑定的Handler对象的dispatchMessage方法,最后,我们看到了handleMessage就在dispatchMessage方法里被调用的。
通过以上的分析,我们可以很清晰的知道Handler、Looper、Message、MessageQueue这四者的关系以及如何合作的了。
5.总结
当调用handler.sendMessage(msg)方法发送一个Message时,实际上这个Message是发送到与当前线程绑定的一个MessageQueue中,然后与当前线程绑定的Looper将会不断的从MessageQueue中取出新的Message,调用msg.target.dispathMessage(msg)方法将消息分发到与Message绑定的handler.handleMessage()方法中。
一个Thread对应多个Handler 一个Thread对应一个Looper和MessageQueue,Handler与Thread共享Looper和MessageQueue。 Message只是消息的载体,将会被发送到与线程绑定的唯一的MessageQueue中,并且被与线程绑定的唯一的Looper分发,被与其自身绑定的Handler消费。
Looper、MessageQueue、Message、Handler的关系的更多相关文章
- Android消息机制:Looper,MessageQueue,Message与handler
Android消息机制好多人都讲过,但是自己去翻源码的时候才能明白. 今天试着讲一下,因为目标是讲清楚整体逻辑,所以不追究细节. Message是消息机制的核心,所以从Message讲起. 1.Mes ...
- 讲讲Handler+Looper+MessageQueue 关系
Handler+Looper+MessageQueue这三者的关系其实就是Android的消息机制.这块内容相比开发人员都不陌生,在面试中,或者日常开发中都会碰到,今天就来讲这三者的关系. 概述: H ...
- Android 异步消息处理机制 让你在深入了解 Looper、Handler、Message之间的关系
转载请注明出处:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 非常多人面试肯定都被问到过,请问And ...
- Android Handler处理机制 ( 三 ) ——Handler,Message,Looper,MessageQueue
在android中提供了一种异步回调机制Handler,使用它,我们可以在完成一个很长时间的任务后做出相应的通知 handler基本使用: 在主线程中,使用handler很简单,new一个Handle ...
- Handler Looper MessageQueue 之间的关系
Handler Looper MessageQueue 之间的关系 handler在安卓开发中常用于更新界面ui,以及其他在主线程中的操作.内部结构大概图为: 1.handler持有一个Looper对 ...
- Android Handler处理机制 ( 二 ) ——Handler,Message,Looper,MessageQueue
Android是消息驱动的,实现消息驱动有几个要素: 消息的表示:Message 消息队列:MessageQueue 消息循环,用于循环取出消息进行处理:Looper 消息处理,消息循环从消息队列中取 ...
- Android Handler处理机制 ( 一 )(图+源码分析)——Handler,Message,Looper,MessageQueue
android的消息处理机制(图+源码分析)——Looper,Handler,Message 作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习 google大牛们的设计思想. ...
- Looper Handler MessageQueue Message 探究
Android消息处理的大致的原理如下: 1.有一个消息队列,可以往队列中添加消息 2.有一个消息循环,可以从消息队列中取出消息 Android系统中这些工作主要由Looper和Handler两个类来 ...
- Android Handler 机制 - Looper,Message,MessageQueue
Android Studio 2.3 API 25 从源码角度分析Handler机制.有利于使用Handler和分析Handler的相关问题. Handler 简介 一个Handler允许发送和处理M ...
随机推荐
- Dell R420 RAID建立以及系统安装
http://thefallenheaven.blog.51cto.com/450907/1753472 Dell R420的RAID划分,以及系统安装 3块2T的盘,装好硬盘后开机,这里有3种方式去 ...
- mingw在Dos下升级gnu编译器版本
在dos窗口下输入: mingw-get update mingw-get upgrade gfortran gcc g++ 强烈建议卸载后再安装新版本
- [Tue, 11 Aug 2015 ~ Mon, 17 Aug 2015] Deep Learning in arxiv
Image Representations and New Domains inNeural Image Captioning we find that a state-of-theart neura ...
- 【iOS系列】-UIButton的非常规使用
[iOS系列]-UIButton的非常规使用 主要介绍UIButton在开发中得小技巧,使用好了,可以达到很奇妙的效果. 1:设置按钮内边距属性,可以呈现出相框的效果 btn.contentEdgeI ...
- Linux Find Out Last System Reboot Time and Date Command 登录安全 开关机 记录 帐号审计 历史记录命令条数
Linux Find Out Last System Reboot Time and Date Command - nixCraft https://www.cyberciti.biz/tips/li ...
- ios移动端浏览器点击事件失效的解决方案
点击事件失效的原因可能是因为,你用了事件代理了, 比如这样 $(document).on("click",".fd",function(){ }) 这段代码在安 ...
- Lightoj 1005 Rooks(DP)
A rook is a piece used in the game of chess which is played on a board of square grids. A rook can o ...
- 替换Android自带apk【转】
本文转载自:http://www.voidcn.com/article/p-gonowdjh-vz.html 安卓自带的app放在/system/app/下,当我们想要替换这些应用时可以参考如下步骤: ...
- HDU2389 Rain on your Parade —— 二分图最大匹配 HK算法
题目链接:https://vjudge.net/problem/HDU-2389 Rain on your Parade Time Limit: 6000/3000 MS (Java/Others) ...
- get the default proxy by Powershell
https://stackoverflow.com/questions/571429/powershell-web-requests-and-proxies $proxyAddr = (get-ite ...