Android从源码分析一:Looper,Handler消息机制

2024-05-24 07:18

本文主要是介绍Android从源码分析一:Looper,Handler消息机制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

首先,大家都知道Android中只能在主线程中做UI处理,当涉及到子线程中更新UI的处理时,就需要一个消息机制把子线程的消息发送到UI线程,这个时候Handler就腾空出世、闪亮登场,来做这个消息的搬运工!
我们来看Handler一般的用法:

Handler myHandler = new Handler() {  // 子类必须重写此方法,接受数据 public void handleMessage(Message msg) {   switch (msg.what) {   //做接受到消息后处理(比如说UI更新)。}   super.handleMessage(msg);   }   };  //子线程里使用Handler发送消息class MyThread implements Runnable { public void run() { try { Thread。sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e。printStackTrace(); }            Message msg = new Message(); Bundle b = new Bundle();// 存放数据 b.putString("color""我的"); msg.setData(b); myHandler.sendMessage(msg); //向Handler发送消息,更新UI } } 
当然发送消息的方式有send系列(sendEmptyMessage(int), sendMessage(Message),sendMessageAtTime(Message,long),sendMessageDelayed(Message, long)>和post( post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long))系列。

下面我们来一步一步的通过源码来解读整个消息的发送和接受的过程。
1、Looper
首先我们还要提一个东西:消息怎么产生的?这里我们要谈一下Looper.有人形象的把它称之为消息泵,不断地从MessageQueue中抽取Message执行。一个MessageQueue需要一个Looper。

对于Looper主要是prepare()和loop()两个方法。
首先看prepare()方法

 private static void prepare(boolean quitAllowed) {if (sThreadLocal.get() != null) {throw new RuntimeException("Only one Looper may be created per thread");}sThreadLocal.set(new Looper(quitAllowed));}

sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。可以看出Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例~否则会抛出异常.

下面是Looper的构造方法:

 private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();}

在构造方法中,创建了一个MessageQueue(消息队列)。
然后我们看loop()方法:

 /*** Run the message queue in this thread. Be sure to call* {@link #quit()} to end the loop.*/public static void loop() {//方法直接返回了sThreadLocal存储的Looper实例,如果me为null则抛出异常,也就是说looper方法必须在prepare方法之后运行。final Looper me = myLooper();if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}//拿到Looper里面的mQueue。final MessageQueue queue = me.mQueue;// 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();
//重头戏来了!进入死循环。for (;;) {Message msg = queue.next(); // might blockif (msg == null) {// 取出一条消息,如果没有消息则阻塞。return;}// This must be in a local variable, in case a UI event sets the loggerPrinter logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}//把消息交给msg的target的dispatchMessage方法去处理,据说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);}//释放资源。msg.recycleUnchecked();}}

总而言之:Looper类用来为一个线程开启一个消息循环:
先调用prepare(),与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
然后调用loop(),不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。
好了,现在消息有了,队列也排好了。就缺一个发送消息的对象了。Handler来也!
2、Handler
我们先来看一下它的构造方法:

public Handler(Callback callback, boolean async) {if (FIND_POTENTIAL_LEAKS) {final Class<? extends Handler> klass = getClass();if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&(klass.getModifiers() & Modifier.STATIC) == 0) {Log.w(TAG, "The following Handler class should be static or leaks might occur: " +klass.getCanonicalName());}}
//获得mLooper对象,通过它获取保存了的MessageQueue(消息队列)。mLooper = Looper.myLooper();if (mLooper == null) {throw new RuntimeException("Can't create handler inside thread that has not called Looper.prepare()");}mQueue = mLooper.mQueue;mCallback = callback;mAsynchronous = async;}

通过 Looper.myLooper();获得mLooper对象,然后又通过mLooper.mQueue获得了mLooper保存的消息队列,这样就保证了Handler与Looper实例中的MessageQueue关联上了。
然后看我们的sendMessage()是怎样发送消息的?
我们从源码中看到,

        sendMessage-->sendEmptyMessageDelayed-->sendMessageDelayed-->sendMessageAtTime:public boolean sendMessageAtTime(Message msg, long uptimeMillis) {MessageQueue queue = mQueue;if (queue == null) {RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");Log.w("Looper", e.getMessage(), e);return false;}return enqueueMessage(queue, msg, uptimeMillis);}

几次调用之后,最终通过sendMessageAtTime()方法内部构建了一个新的MessageQueue ,并且将其与传过来的Message一起调用了enqueueMessage()方法,我们再来看:

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {//把Handler对象作为Looper里面的msg.target;并将msg通过MessageQueue类放到消息队列里面。最终把这个消息发送出去。msg.target = this;if (mAsynchronous) {msg.setAsynchronous(true);}return queue.enqueueMessage(msg, uptimeMillis);}

如果大家有心,应该会记得Looper里面的loop()方法中的无限循环里面的

 msg.target.dispatchMessage(msg);//最终Looper交给msg.target去处理,

而今,handler里面将msg.targer赋值为this;也就是把当前的handler作为msg的target属性。最终会调用MessageQueue 的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去!
现在已经很清楚了,就是Looper会调用perpare和loop方法,在当前执行的线程中保存一个Looper实例,并且这个实例会保存一个MessageQueue对象,然后当前线程进入无限循环当中,不断从MessageQueue中读取msg.target也就是Handler发送过来的消息。接下来我们就看Handler是如何接收的:刚刚说到了

      msg.target.dispatchMessage(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);}}

无论如何最终都调用了handleMessage();
下面我们来看一下handleMesssage()这个方法:

/*** Subclasses must implement this to receive messages.*/public void handleMessage(Message msg) {}

空的,上面的注释是说,子类必须重写这个方法来接收消息。所以知道我们为啥写Handler的时候都要重写handleMessage()方法了吧!

这篇关于Android从源码分析一:Looper,Handler消息机制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/997737

相关文章

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

Java中Springboot集成Kafka实现消息发送和接收功能

《Java中Springboot集成Kafka实现消息发送和接收功能》Kafka是一个高吞吐量的分布式发布-订阅消息系统,主要用于处理大规模数据流,它由生产者、消费者、主题、分区和代理等组件构成,Ka... 目录一、Kafka 简介二、Kafka 功能三、POM依赖四、配置文件五、生产者六、消费者一、Kaf

一文带你理解Python中import机制与importlib的妙用

《一文带你理解Python中import机制与importlib的妙用》在Python编程的世界里,import语句是开发者最常用的工具之一,它就像一把钥匙,打开了通往各种功能和库的大门,下面就跟随小... 目录一、python import机制概述1.1 import语句的基本用法1.2 模块缓存机制1.

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis缓存问题与缓存更新机制详解

《Redis缓存问题与缓存更新机制详解》本文主要介绍了缓存问题及其解决方案,包括缓存穿透、缓存击穿、缓存雪崩等问题的成因以及相应的预防和解决方法,同时,还详细探讨了缓存更新机制,包括不同情况下的缓存更... 目录一、缓存问题1.1 缓存穿透1.1.1 问题来源1.1.2 解决方案1.2 缓存击穿1.2.1

Java如何通过反射机制获取数据类对象的属性及方法

《Java如何通过反射机制获取数据类对象的属性及方法》文章介绍了如何使用Java反射机制获取类对象的所有属性及其对应的get、set方法,以及如何通过反射机制实现类对象的实例化,感兴趣的朋友跟随小编一... 目录一、通过反射机制获取类对象的所有属性以及相应的get、set方法1.遍历类对象的所有属性2.获取

MySQL中的锁和MVCC机制解读

《MySQL中的锁和MVCC机制解读》MySQL事务、锁和MVCC机制是确保数据库操作原子性、一致性和隔离性的关键,事务必须遵循ACID原则,锁的类型包括表级锁、行级锁和意向锁,MVCC通过非锁定读和... 目录mysql的锁和MVCC机制事务的概念与ACID特性锁的类型及其工作机制锁的粒度与性能影响多版本

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步