Handler+Looper+MessageQueue深入详解

2023-12-10 07:58

本文主要是介绍Handler+Looper+MessageQueue深入详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这一篇我们将深入学习Android线程间通讯的实现原理。

概述:Android使用消息机制实现线程间的通信,线程通过Looper建立自己的消息循环,MessageQueue是FIFO的消息队列,Looper负责从MessageQueue中取出消息,并且分发到消息指定目标Handler对象。Handler对象绑定到线程的局部变量Looper,封装了发送消息和处理消息的接口。

例子:在介绍原理之前,我们先介绍Android线程通讯的一个例子,这个例子实现点击按钮之后从主线程发送消息"hello"到另外一个名为” CustomThread”的线程。

代码下载

LooperThreadActivity.java

01 package com.zhuozhuo;
02  
03 import android.app.Activity;
04 import android.os.Bundle;
05 import android.os.Handler;
06 import android.os.Looper;
07 import android.os.Message;
08 import android.util.Log;
09 import android.view.View;
10 import android.view.View.OnClickListener;
11  
12 public class LooperThreadActivity extends Activity{
13     /** Called when the activity is first created. */
14      
15     private final int MSG_HELLO = 0;
16     private Handler mHandler;
17      
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22         new CustomThread().start();//新建并启动CustomThread实例
23          
24         findViewById(R.id.send_btn).setOnClickListener(new OnClickListener() {
25              
26             @Override
27             public void onClick(View v) {//点击界面时发送消息
28                 String str = "hello";
29                 Log.d("Test""MainThread is ready to send msg:" + str);
30                 mHandler.obtainMessage(MSG_HELLO, str).sendToTarget();//发送消息到CustomThread实例
31                  
32             }
33         });
34          
35     }
36      
37      
38      
39      
40      
41     class CustomThread extends Thread {
42         @Override
43         public void run() {
44             //建立消息循环的步骤
45             Looper.prepare();//1、初始化Looper
46             mHandler = new Handler(){//2、绑定handler到CustomThread实例的Looper对象
47                 public void handleMessage (Message msg) {//3、定义处理消息的方法
48                     switch(msg.what) {
49                     case MSG_HELLO:
50                         Log.d("Test""CustomThread receive msg:" + (String) msg.obj);
51                     }
52                 }
53             };
54             Looper.loop();//4、启动消息循环
55         }
56     }
57 }

main.xml

01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:orientation="vertical"
04     android:layout_width="fill_parent"
05     android:layout_height="fill_parent"
06     >
07 <TextView 
08     android:layout_width="fill_parent"
09     android:layout_height="wrap_content"
10     android:text="@string/hello"
11     />
12 <Button android:text="发送消息" android:id="@+id/send_btn"android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
13 </LinearLayout>

Log打印结果:

原理:

我们看到,为一个线程建立消息循环有四个步骤:

1、 初始化Looper

2、 绑定handler到CustomThread实例的Looper对象

3、 定义处理消息的方法

4、 启动消息循环

下面我们以这个例子为线索,深入Android源代码,说明Android Framework是如何建立消息循环,并对消息进行分发的。

1、 初始化Looper : Looper.prepare()

Looper.java

1 private static final ThreadLocal sThreadLocal = new ThreadLocal();
2 public static final void prepare() {
3         if (sThreadLocal.get() != null) {
4             throw new RuntimeException("Only one Looper may be created per thread");
5         }
6         sThreadLocal.set(new Looper());
7 }

一个线程在调用Looper的静态方法prepare()时,这个线程会新建一个Looper对象,并放入到线程的局部变量中,而这个变量是不和其他线程共享的(关于ThreadLocal的介绍)。下面我们看看Looper()这个构造函数:

Looper.java

1 final MessageQueue mQueue;
2 private Looper() {
3         mQueue = new MessageQueue();
4         mRun = true;
5         mThread = Thread.currentThread();
6     }

可以看到在Looper的构造函数中,创建了一个消息队列对象mQueue,此时,调用Looper. prepare()的线程就建立起一个消息循环的对象(此时还没开始进行消息循环)。

2、 绑定handler到CustomThread实例的Looper对象 : mHandler= new Handler()

Handler.java

01 final MessageQueue mQueue;
02  final Looper mLooper;
03 public Handler() {
04         if (FIND_POTENTIAL_LEAKS) {
05             final Class<? extends Handler> klass = getClass();
06             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
07                     (klass.getModifiers() & Modifier.STATIC) == 0) {
08                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
09                     klass.getCanonicalName());
10             }
11         }
12  
13         mLooper = Looper.myLooper();
14         if (mLooper == null) {
15             throw new RuntimeException(
16                 "Can't create handler inside thread that has not called Looper.prepare()");
17         }
18         mQueue = mLooper.mQueue;
19         mCallback = null;
20 }

Handler通过mLooper = Looper.myLooper();绑定到线程的局部变量Looper上去,同时Handler通过mQueue =mLooper.mQueue;获得线程的消息队列。此时,Handler就绑定到创建此Handler对象的线程的消息队列上了。

3、定义处理消息的方法:Override public void handleMessage (Message msg){} 

子类需要覆盖这个方法,实现接受到消息后的处理方法。

4、启动消息循环 : Looper.loop()

所有准备工作都准备好了,是时候启动消息循环了!Looper的静态方法loop()实现了消息循环。

Looper.java

01 public static final void loop() {
02        Looper me = myLooper();
03        MessageQueue queue = me.mQueue;
04         
05        // Make sure the identity of this thread is that of the local process,
06        // and keep track of what that identity token actually is.
07        Binder.clearCallingIdentity();
08        final long ident = Binder.clearCallingIdentity();
09         
10        while (true) {
11            Message msg = queue.next(); // might block
12            //if (!me.mRun) {
13            //    break;
14            //}
15            if (msg != null) {
16                if (msg.target == null) {
17                    // No target is a magic identifier for the quit message.
18                    return;
19                }
20                if (me.mLogging!= null) me.mLogging.println(
21                        ">>>>> Dispatching to " + msg.target + " "
22                        + msg.callback + ": " + msg.what
23                        );
24                msg.target.dispatchMessage(msg);
25                if (me.mLogging!= null) me.mLogging.println(
26                        "<<<<< Finished to    " + msg.target + " "
27                        + msg.callback);
28                 
29                // Make sure that during the course of dispatching the
30                // identity of the thread wasn't corrupted.
31                final long newIdent = Binder.clearCallingIdentity();
32                if (ident != newIdent) {
33                    Log.wtf("Looper""Thread identity changed from 0x"
34                            + Long.toHexString(ident) + " to 0x"
35                            + Long.toHexString(newIdent) + " while dispatching to "
36                            + msg.target.getClass().getName() + " "
37                            + msg.callback + " what=" + msg.what);
38                }
39                 
40                msg.recycle();
41            }
42        }
43    }

while(true)体现了消息循环中的“循环“,Looper会在循环体中调用queue.next()获取消息队列中需要处理的下一条消息。当msg != null且msg.target != null时,调用msg.target.dispatchMessage(msg);分发消息,当分发完成后,调用msg.recycle();回收消息。

msg.target是一个handler对象,表示需要处理这个消息的handler对象。Handler的void dispatchMessage(Message msg)方法如下:

Handler.java

01 public void dispatchMessage(Message msg) {
02         if (msg.callback != null) {
03             handleCallback(msg);
04         else {
05             if (mCallback != null) {
06                 if (mCallback.handleMessage(msg)) {
07                     return;
08                 }
09             }
10             handleMessage(msg);
11         }
12 }

可见,当msg.callback== null 并且mCallback == null时,这个例子是由handleMessage(msg);处理消息,上面我们说到子类覆盖这个方法可以实现消息的具体处理过程。

总结:从上面的分析过程可知,消息循环的核心是Looper,Looper持有消息队列MessageQueue对象,一个线程可以把Looper设为该线程的局部变量,这就相当于这个线程建立了一个对应的消息队列。Handler的作用就是封装发送消息和处理消息的过程,让其他线程只需要操作Handler就可以发消息给创建Handler的线程。由此可以知道,在上一篇《Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面》中,UI线程在创建的时候就建立了消息循环(在ActivityThread的public static final void main(String[] args)方法中实现),因此我们可以在其他线程给UI线程的handler发送消息,达到更新UI的目的。

文章转自:http://blog.csdn.net/mylzc/article/details/6771331


这篇关于Handler+Looper+MessageQueue深入详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/476489

相关文章

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

C#读写文本文件的多种方式详解

《C#读写文本文件的多种方式详解》这篇文章主要为大家详细介绍了C#中各种常用的文件读写方式,包括文本文件,二进制文件、CSV文件、JSON文件等,有需要的小伙伴可以参考一下... 目录一、文本文件读写1. 使用 File 类的静态方法2. 使用 StreamReader 和 StreamWriter二、二进

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注