Android的Handler,Looper源码剖析

2024-04-26 12:08

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

之前了解android的消息处理机制,但是源码看的少,现在把Looper,Handler,Message这几个类的源码分析一哈

android的消息处理有三个核心类:Looper,Handler和Message。其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因此我没将其作为核心类

Looper源码:

Looper的字面意思是“循环者”,它被设计用来使一个普通线程变成Looper线程。所谓Looper线程就是循环工作的线程

使用Looper类创建Looper线程Demo:

public class LooperThread extends Thread {@Overridepublic void run() {// 将当前线程初始化为Looper线程Looper.prepare();// ...其他处理,如实例化handler// 开始循环处理消息队列Looper.loop();}
}
1)Looper.prepare()源码

public final class Looper {private static final String TAG = "Looper";// sThreadLocal.get() will return null unless you've called prepare()./*如果没有调用prepare将Looper对象设置为线程的本地变量,则sThreadLocal.get()为空*//*// 每个线程中的Looper对象其实是一个ThreadLocal,即线程本地存储(TLS)对象*/static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//当前线程的本地变量private static Looper sMainLooper;  // guarded by Looper.classfinal MessageQueue mQueue;//Looper维护的消息队列MQfinal Thread mThread;//Looper关联的当前线程private Printer mLogging;/** Initialize the current thread as a looper.* This gives you a chance to create handlers that then reference* this looper, before actually starting the loop. Be sure to call* {@link #loop()} after calling this method, and end it by calling* {@link #quit()}.*/public static void prepare() {prepare(true);}/* 我们调用该方法会在调用线程的TLS中创建Looper对象*/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));//就是把Looper对象设置为当前线程的一个本地变量}

                                                      Prepare()之后的的图:

                                                       

现在你的线程中有一个Looper对象,它的内部维护了一个消息队列MQ。注意,一个Thread只能有一个Looper对象
2)Looper.loop()源码

    /*** Run the message queue in this thread. Be sure to call* {@link #quit()} to end the loop.*在当前线程中执行消息队列,确定调用quit()结束循环*/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;//获得Loop对象关联的消息队列/*没看懂,不影响理解*/ // 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 block,从消息队列中获取消息Messageif (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 loggerPrinter 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);}msg.recycleUnchecked();   // 回收message资源}}/*** Return the Looper object associated with the current thread.  Returns* null if the calling thread is not associated with a Looper.*返回与当前线程相关联的Looper对象*/public static Looper myLooper() {return sThreadLocal.get();//其实就是从线程的本地变量里面取值}/*** Return the {@link MessageQueue} object associated with the current* thread.  This must be called from a thread running a Looper, or a* NullPointerException will be thrown.* 返回与当前线程相关联的MessageQueue对象*/public static MessageQueue myQueue() {return myLooper().mQueue;}/*初始化Looper的两个属性,关联的线程和消息队列*/private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();}
调用loop方法后,Looper线程就开始真正工作了,它不断从自己的MQ中取出队头的消息(也叫任务)执行

                   
Looper有了基本的了解,总结几点:
1.每个线程有且最多只能有一个Looper对象,它是一个ThreadLocal就是Looper对象
2.Looper内部有一个消息队列,loop()方法调用后线程开始不断从队列中取出消息执行
3.Looper使一个线程变成Looper线程

那么,我们如何往MQ上添加消息呢?下面有请Handler

Handler分析:

handler扮演了往MQ上添加消息和处理消息的角色(只处理由自己发出的消息),即通知MQ它要执行一个任务(sendMessage),并在loop到自己的时候执行该任务(handleMessage),整个过程是异步的。handler创建时会关联一个looper,默认的构造方法将关联当前线程的looper,不过这也是可以set的

为之前的LooperThread类加入Handler:

public class LooperThread extends Thread {private Handler handler1;private Handler handler2;@Overridepublic void run() {// 将当前线程初始化为Looper线程Looper.prepare();// 实例化两个handlerhandler1 = new Handler();// 开始循环处理消息队列Looper.loop();}
}
加入handler后的效果:



1,Handler发送消息

可以使用

post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long)和 sendMessageDelayed(Message, long)这些方法向MQ上发送消息了。光看这些API你可能会觉得handler能发两种消息,一种是Runnable对象,一种是message对象,这是直观的理解,但其实post发出的Runnable对象最后都被封装成message对象

/*** Causes the Runnable r to be added to the message queue.* The runnable will be run on the thread to which this handler is * attached. *  * @param r The Runnable that will be executed.* * @return Returns true if the Runnable was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.*//*把一个Runnable对象加入消息队列,任务将在当前Handler绑定的线程中执行,说白了就是当前线程执行任务*/public final boolean post(Runnable r){return  sendMessageDelayed(getPostMessage(r), 0);}/*** Causes the Runnable r to be added to the message queue, to be run* at a specific time given by <var>uptimeMillis</var>.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.* The runnable will be run on the thread to which this handler is attached.** @param r The Runnable that will be executed.* @param uptimeMillis The absolute time at which the callback should run,*         using the {@link android.os.SystemClock#uptimeMillis} time-base.*  * @return Returns true if the Runnable was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.  Note that a*         result of true does not mean the Runnable will be processed -- if*         the looper is quit before the delivery time of the message*         occurs then the message will be dropped.*/public final boolean postAtTime(Runnable r, long uptimeMillis){return sendMessageAtTime(getPostMessage(r), uptimeMillis);}/*** Causes the Runnable r to be added to the message queue, to be run* at a specific time given by <var>uptimeMillis</var>.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.* The runnable will be run on the thread to which this handler is attached.** @param r The Runnable that will be executed.* @param uptimeMillis The absolute time at which the callback should run,*         using the {@link android.os.SystemClock#uptimeMillis} time-base.* * @return Returns true if the Runnable was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.  Note that a*         result of true does not mean the Runnable will be processed -- if*         the looper is quit before the delivery time of the message*         occurs then the message will be dropped.*         * @see android.os.SystemClock#uptimeMillis*/public final boolean postAtTime(Runnable r, Object token, long uptimeMillis){return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);}/*** Causes the Runnable r to be added to the message queue, to be run* after the specified amount of time elapses.* The runnable will be run on the thread to which this handler* is attached.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.*  * @param r The Runnable that will be executed.* @param delayMillis The delay (in milliseconds) until the Runnable*        will be executed.*        * @return Returns true if the Runnable was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.  Note that a*         result of true does not mean the Runnable will be processed --*         if the looper is quit before the delivery time of the message*         occurs then the message will be dropped.*/public final boolean postDelayed(Runnable r, long delayMillis){return sendMessageDelayed(getPostMessage(r), delayMillis);}/*** Posts a message to an object that implements Runnable.* Causes the Runnable r to executed on the next iteration through the* message queue. The runnable will be run on the thread to which this* handler is attached.* <b>This method is only for use in very special circumstances -- it* can easily starve the message queue, cause ordering problems, or have* other unexpected side-effects.</b>*  * @param r The Runnable that will be executed.* * @return Returns true if the message was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.*/public final boolean postAtFrontOfQueue(Runnable r){return sendMessageAtFrontOfQueue(getPostMessage(r));}/*** Pushes a message onto the end of the message queue after all pending messages* before the current time. It will be received in {@link #handleMessage},* in the thread attached to this handler.*  * @return Returns true if the message was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.*//*把一个消息放入消息队列中,返回true*/public final boolean sendMessage(Message msg){return sendMessageDelayed(msg, 0);}/*** Sends a Message containing only the what value.*  * @return Returns true if the message was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.*//*把一个只有what的消息放入到消息队列中*/public final boolean sendEmptyMessage(int what){return sendEmptyMessageDelayed(what, 0);}/*** Sends a Message containing only the what value, to be delivered* after the specified amount of time elapses.* @see #sendMessageDelayed(android.os.Message, long) * * @return Returns true if the message was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.*/public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {Message msg = Message.obtain();msg.what = what;return sendMessageDelayed(msg, delayMillis);}/*** Sends a Message containing only the what value, to be delivered * at a specific time.* @see #sendMessageAtTime(android.os.Message, long)*  * @return Returns true if the message was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.*/public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {Message msg = Message.obtain();msg.what = what;return sendMessageAtTime(msg, uptimeMillis);}/*** Enqueue a message into the message queue after all pending messages* before (current time + delayMillis). You will receive it in* {@link #handleMessage}, in the thread attached to this handler.*  * @return Returns true if the message was successfully placed in to the *         message queue.  Returns false on failure, usually because the*         looper processing the message queue is exiting.  Note that a*         result of true does not mean the message will be processed -- if*         the looper is quit before the delivery time of the message*         occurs then the message will be dropped.*/public final boolean sendMessageDelayed(Message msg, long delayMillis){if (delayMillis < 0) {delayMillis = 0;}return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);}
Handler处理消息:

/*** Subclasses must implement this to receive messages.*子类必须实现这个方法接收消息*/public void handleMessage(Message msg) {}/*** Handle system messages here.*处理系统的消息, 处理消息,该方法由looper调用   msg.target.dispatchMessage(msg);就是把消息交给Handler来处理*/public void dispatchMessage(Message msg) {if (msg.callback != null) {// 如果message设置了callback,即runnable消息,处理callback!handleCallback(msg);} else {// 如果handler本身设置了callback,则执行callbackif (mCallback != null) {/* 这种方法允许让activity等来实现Handler.Callback接口,避免了自己编写handler重写handleMessage方法*/if (mCallback.handleMessage(msg)) {return;}}// 如果message没有callback,则调用handler的钩子方法handleMessagehandleMessage(msg);}}

相关理论看之前的文章http://blog.csdn.net/tuke_tuke/article/details/50783153


这篇关于Android的Handler,Looper源码剖析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

Java ArrayList扩容机制 (源码解读)

结论:初始长度为10,若所需长度小于1.5倍原长度,则按照1.5倍扩容。若不够用则按照所需长度扩容。 一. 明确类内部重要变量含义         1:数组默认长度         2:这是一个共享的空数组实例,用于明确创建长度为0时的ArrayList ,比如通过 new ArrayList<>(0),ArrayList 内部的数组 elementData 会指向这个 EMPTY_EL

如何在Visual Studio中调试.NET源码

今天偶然在看别人代码时,发现在他的代码里使用了Any判断List<T>是否为空。 我一般的做法是先判断是否为null,再判断Count。 看了一下Count的源码如下: 1 [__DynamicallyInvokable]2 public int Count3 {4 [__DynamicallyInvokable]5 get

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、

android-opencv-jni

//------------------start opencv--------------------@Override public void onResume(){ super.onResume(); //通过OpenCV引擎服务加载并初始化OpenCV类库,所谓OpenCV引擎服务即是 //OpenCV_2.4.3.2_Manager_2.4_*.apk程序包,存

从状态管理到性能优化:全面解析 Android Compose

文章目录 引言一、Android Compose基本概念1.1 什么是Android Compose?1.2 Compose的优势1.3 如何在项目中使用Compose 二、Compose中的状态管理2.1 状态管理的重要性2.2 Compose中的状态和数据流2.3 使用State和MutableState处理状态2.4 通过ViewModel进行状态管理 三、Compose中的列表和滚动

Spring 源码解读:自定义实现Bean定义的注册与解析

引言 在Spring框架中,Bean的注册与解析是整个依赖注入流程的核心步骤。通过Bean定义,Spring容器知道如何创建、配置和管理每个Bean实例。本篇文章将通过实现一个简化版的Bean定义注册与解析机制,帮助你理解Spring框架背后的设计逻辑。我们还将对比Spring中的BeanDefinition和BeanDefinitionRegistry,以全面掌握Bean注册和解析的核心原理。

Android 10.0 mtk平板camera2横屏预览旋转90度横屏拍照图片旋转90度功能实现

1.前言 在10.0的系统rom定制化开发中,在进行一些平板等默认横屏的设备开发的过程中,需要在进入camera2的 时候,默认预览图像也是需要横屏显示的,在上一篇已经实现了横屏预览功能,然后发现横屏预览后,拍照保存的图片 依然是竖屏的,所以说同样需要将图片也保存为横屏图标了,所以就需要看下mtk的camera2的相关横屏保存图片功能, 如何实现实现横屏保存图片功能 如图所示: 2.mtk