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个 ...
随机推荐
- UVALive 4764 简单dp水题(也可以暴力求解)
B - Bing it Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu Submit Status ...
- zoj3161 Damn Couples
不想打题面了,题面戳这里 这道题目的模型转换地有点猛.首先我们肯定需要让老板把那些不相邻的人的卡牌放在前面,这样他们就作废了.然后剩下的卡牌就都是相邻人之间的了.我们就可以把这个序列分成若干个联通块, ...
- 刷题总结——Interval query(hdu4343倍增+贪心)
题目: Problem Description This is a very simple question. There are N intervals in number axis, and M ...
- Recompile Squid with SSL Bump
https://docs.diladele.com/administrator_guide_4_0/system_configuration/https_filtering/recompile_squ ...
- windows 系统下git 的安装
在linux系统下,可以直接在命令窗口安装和使用git.但是,在windows系统下,想要达到同样的效果,可以安装git,使用git bash到达效果.具体安装步骤如下: 第一步:官网上下载git 网 ...
- CodeForces - 789B B. Masha and geometric depression---(水坑 分类讨论)
CodeForces - 789B 当时题意理解的有点偏差,一直wa在了14组.是q等于0的时候,b1的绝对值大于l的时候,当b1的绝对值大于l的时候就应该直接终端掉,不应该管后面的0的. 题意告诉你 ...
- 【转】beyond compare 启动提示“应用程序发生错误”
[转]beyond compare 启动提示“应用程序发生错误” 今天到公司BCompare不能打开,重新安装也不能打开.最后处理下,就解决了.方法是把C:\Documents and Setti ...
- 整数拆分问题_C++
一.问题背景 整数拆分,指把一个整数分解成若干个整数的和 如 3=2+1=1+1+1 共2种拆分 我们认为2+1与1+2为同一种拆分 二.定义 在整数n的拆分中,最大的拆分数为m,我们记它的方案数 ...
- eclipse非主窗口的停靠(正常), 恢复, 最小化, 最大化的切换
1. pydev package Explorer的停靠与内嵌等 正常的情况
- CGRectInset、CGRectOffset、等对比整理
http://blog.sina.com.cn/s/blog_76f3236b01013zmk.html 分类: iphone有关 1.CGRectInsetCGRect CGRectInset ...