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

相关文章

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I

Android 实现一个隐私弹窗功能

《Android实现一个隐私弹窗功能》:本文主要介绍Android实现一个隐私弹窗功能,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 效果图如下:1. 设置同意、退出、点击用户协议、点击隐私协议的函数参数2. 《用户协议》、《隐私政策》设置成可点击的,且颜色要区分出来res/l

Android实现一键录屏功能(附源码)

《Android实现一键录屏功能(附源码)》在Android5.0及以上版本,系统提供了MediaProjectionAPI,允许应用在用户授权下录制屏幕内容并输出到视频文件,所以本文将基于此实现一个... 目录一、项目介绍二、相关技术与原理三、系统权限与用户授权四、项目架构与流程五、环境配置与依赖六、完整

Android 12解决push framework.jar无法开机的方法小结

《Android12解决pushframework.jar无法开机的方法小结》:本文主要介绍在Android12中解决pushframework.jar无法开机的方法,包括编译指令、框架层和s... 目录1. android 编译指令1.1 framework层的编译指令1.2 替换framework.ja

Android开发环境配置避坑指南

《Android开发环境配置避坑指南》本文主要介绍了Android开发环境配置过程中遇到的问题及解决方案,包括VPN注意事项、工具版本统一、Gerrit邮箱配置、Git拉取和提交代码、MergevsR... 目录网络环境:VPN 注意事项工具版本统一:android Studio & JDKGerrit的邮

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE