Android Handler 消息循环机制
前言
一问起Android应用程序的入口,很多人会说是Activity中的onCreate方法,也有人说是ActivityThread中的静态main方法。因为Java虚拟机在运行的时候会自动加载指定类的静态共有main方法,因此个人更倾向于第二种说法。
- public final class ActivityThread {
- ......
- public static void main(String[] args) {
- ......
- Looper.prepareMainLooper();
- ActivityThread thread = new ActivityThread();
- thread.attach(false);
- if (sMainThreadHandler == null) {
- sMainThreadHandler = thread.getHandler();
- }
- ......
- Looper.loop();
- throw new RuntimeException("Main thread loop unexpectedly exited");
- }
- }
我们注意到这段代码,先调用Looper的prepareMainLooper()方法,新建一个ActivityThread,然后再获取MainThreadHander,最后调用Looper.loop()方法,程序就一直在loop方法中循环。Looper,Handler之间有何关系?请看下文。
程序的消息循环
- class test {
- public static void main (String[] args) {
- System.out.println("hello world!");
- }
- }
上述小程序就是一个任务,虚拟机启用一个线程执行完该任务后,程序就结束了。为了保证程序不立即退出,一般都会写一个循环
- class test {
- public static void main (String[] args) {
- while (hasNextMessage()) {
- msg = getMessage() ;
- handleMessage(msg) ;
- }
- }
- }
系统不断从getMessage获取消息,再通过handleMessage来处理消息。这种基于消息的循环模型在许多的系统框架中都有实现。比如iOS系统中的RunLoop,再比如windows系统中的消息队列,windows系统会为每一个UI线程分配一个消息队列,发生输入事件后,windows将事件转换为一个"消息"发送给系统消息队列,操作系统有一个专门的线程从系统消息队列中取出消息,分发给各个UI线程的输入消息队列中。Android中的应用系统框架也不例外,也有一套自己的消息循环机制,这套机制是靠Looper、Handler、MessageQueue来共同完成的。
原理

图片来自zongpeiqing的CSDN博客。Looper负责消息循环(例子中的while语句),Handler负责发送和处理消息,MessageQueue则负责管理消息(消息的增加和移除)。不管是sendMessage还是sendMessageDelay或是View.post方法,或是上面列出的没列出的发送消息的方法,最终都会包装成一条消息Message(这条消息由Handler发出),然后调用MessageQuque的enqueueMessage方法把消息放到消息队列MessageQueue中。而Looper则会不停地查看MessageQueue中是否有新消息msg,有新消息就会调用新消息msg.target.handleMessage()去处理消息,否则会一直阻塞。msg.target实际上是Handler对象。因此,Handler发送的消息,最终也是由Handler来处理。
问题
Q1: Handler是怎么在不同线程之间切换的?
- public final class Looper {
- ......
- 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;
- }
- ......
- msg.target.dispatchMessage(msg);
- ......
- msg.recycleUnchecked();
- }
- }
- }
- public class Handler {
- /*
- * Set this flag to true to detect anonymous, local or member classes
- * that extend this Handler class and that are not static. These kind
- * of classes can potentially create leaks.
- */
- private static final boolean FIND_POTENTIAL_LEAKS = false;
- private static final String TAG = "Handler";
- /**
- * 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);
- }
- /**
- * Subclasses must implement this to receive messages.
- */
- public void handleMessage(Message msg) {
- }
- /**
- * 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);
- }
- }
- }
首先在线程1新建一个handler,在线程2 新建一条消息msg,然后在线程2调用hander.sendMessage(msg),因为在handler的处理逻辑handleMessage()方法是放在线程1的,因此在线程2中调用了hander.sendMessage(msg),MessagQueue插入了这条消息,Looper发现有新消息,然后取出新消息,调用msg.target.dispatchMessage(msg),上面已经说到,target其实是hander,这样便成功地切换到线程1的handleMessage逻辑上来了。最常见的例子就是在Activity中声明一个Handler,然后异步线程去请求网络,再通过网络更新UI。可以参考这里。
Q2: 上面的模型中,为何不直接使用Handler来循环消息?
这个问题仁者见仁,智者见智,这只是一种实现消息循环的方法之一,而不是唯一方法。不是说一定要用Looper。
Q3: 需要注意的点?
使用Looper前一定要调用Looper.prepare生成线程内(TheadLocal存储)的Looper实例,然后才能调用Looper.loop()实现消息循环。下面是一个非主线程中Looper和Handler演示例子,此时整个线程是不会自动停止的,会一直阻塞,直到调用了Looper.quit()方法才会停止。(下面代码仅仅是为了演示,没有做任何事)
- new Thread("example-1") {
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- // 自己的处理逻辑
- if (条件满足) {
- Looper.quit() ; //退出消息循环,结束线程
- }
- }
- } ;
- @Override
- public void run() {
- Looper.prepare();
- // do something....
- Message msg = Message.obtain();
- msg.what = ...
- msg.obj = ...
- .......
- handler.sendMessage(msg);
- Looper.loop();
- }
- }.start() ;
Q4: 为何ActivityThread中的Looper.loop()没有阻塞主线程?
。。。。。
参考
Android Handler 消息循环机制的更多相关文章
- Android的消息循环机制 Looper Handler类分析
Android的消息循环机制 Looper Handler类分析 Looper类说明 Looper 类用来为一个线程跑一个消息循环. 线程在默认情况下是没有消息循环与之关联的,Thread类在ru ...
- Android HandlerThread 消息循环机制之源代码解析
关于 HandlerThread 这个类.可能有些人眼睛一瞟,手指放在键盘上,然后就是一阵狂敲.立即就能敲出一段段华丽的代码: HandlerThread handlerThread = new Ha ...
- 安卓中的消息循环机制Handler及Looper详解
我们知道安卓中的UI线程不是线程安全的,我们不能在UI线程中进行耗时操作,通常我们的做法是开启一个子线程在子线程中处理耗时操作,但是安卓规定不允许在子线程中进行UI的更新操作,通常我们会通过Handl ...
- System、应用程序进程的Binder线程池和Handler消息循环
首先看一张Android系统启动流程图:
- Dart异步与消息循环机制
Dart与消息循环机制 翻译自https://www.dartlang.org/articles/event-loop/ 异步任务在Dart中随处可见,例如许多库的方法调用都会返回Future对象来实 ...
- 【Dart学习】-- Dart之消息循环机制[翻译]
概述 异步任务在Dart中随处可见,例如许多库的方法调用都会返回Future对象来实现异步处理,我们也可以注册Handler来响应一些事件,如:鼠标点击事件,I/O流结束和定时器到期. 这篇文章主要介 ...
- Win32消息循环机制等【转载】http://blog.csdn.net/u013777351/article/details/49522219
Dos的过程驱动与Windows的事件驱动 在讲本程序的消息循环之前,我想先谈一下Dos与Windows驱动机制的区别: DOS程序主要使用顺序的,过程驱动的程序设计方法.顺序的,过程驱动的程序有一个 ...
- Android Handler消息机制不完全解析
1.Handler的作用 Android开发中,我们经常使用Handler进行页面的更新.例如我们需要在一个下载任务完成后,去更新我们的UI效果,因为AndroidUI操作不是线程安全的,也就意味着我 ...
- Android Handler消息机制源码解析
好记性不如烂笔头,今天来分析一下Handler的源码实现 Handler机制是Android系统的基础,是多线程之间切换的基础.下面我们分析一下Handler的源码实现. Handler消息机制有4个 ...
随机推荐
- 201621123034 《Java程序设计》第10周学习总结
作业10-异常 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常相关内容. 2. 书面作业 本次PTA作业题集异常 1. 常用异常 结合题集题目7-1回答 1.1 自己以前编写 ...
- POJ 2186 受欢迎的牛 Tarjan基础题
#include<cstdio> #include<algorithm> #include<cstring> #include<vector> #inc ...
- 基于RRT的机器人自主探索建图
一.方法讲解: 本项目分为三个部分:机器人周围一定范围内基于RRT的全局检测, 根据上一步检测的未知区域点执行sklearn.cluster.MeanShift聚类,获取聚类中心: 根据聚类中心计算各 ...
- Codeforces Round #355 (Div. 2) C 预处理
C. Vanya and Label time limit per test 1 second memory limit per test 256 megabytes input standard i ...
- 行为型设计模式之访问者模式(Visitor)
结构 意图 表示一个作用于某对象结构中的各元素的操作.它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作. 适用性 一个对象结构包含很多类对象,它们有不同的接口,而你想对这些对象实施一些依 ...
- Linux Mint---开启桌面三维特效
其实系统默认已经安装好了compiz,我们只需要切换就可以了 menu->control center->desktop setting->window 开启compiz的时候,由于 ...
- Grep查看日志的方法【转】
转自:http://blog.csdn.net/stormkey/article/details/5905204 版权声明 :转载时请以超链接形式标明文章原始出处和作者信息及本声明 http://go ...
- spark streaming 异常No output streams registered, so nothing to execute
实现spark streaming demo时,代码: public static void main (String[] args) { SparkConf conf = new SparkConf ...
- android的百度地图开发(一)
1,注册百度开发者账号 2,申请key ,注意开发版SH和发布版的SH 获取开发版SHA1: 输入命令:keytool -list -v -keystore debug.keystore,回车输入 ...
- django中的类视图
# 原创,转载请留言联系 当我们在开发一个注册模块时.浏览器会通过get请求让注册表单弹出来,然后用户输完注册信息后,通过post请求向服务端提交信息.这时候我们后端有两个视图函数,一个处理get请求 ...