Android进阶系列之2:HandlerThread详解

2024-03-23 19:48

本文主要是介绍Android进阶系列之2:HandlerThread详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 HandlerThread介绍

HandlerThread的本质其实就是Thread封装了Looper。默认情况下,开启一个新的线程时,不会有Looper循环。HandlerThread带个我们的功能是:当开启一个新的线程时,默认帮我们建立好消息循环。方便我们的使用。

2 HandlerThread使用例子

public class MyActivity extends Activity {private static final String TAG = "Test-Handler-Thread";private static final int MESSAGE_FROM_MAIN_THREAD = 1;private static final int MESSAGE_FROM_WORK_THREAD = 2;private HandlerThread mHandlerThread;private Handler mHandler;/*** Called when the activity is first created.*/@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mHandlerThread = new HandlerThread("Handler-Thread");mHandlerThread.start();mHandler = new Handler(mHandlerThread.getLooper()) {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case MESSAGE_FROM_MAIN_THREAD:Log.d(TAG, "msg from main thread, handleMessage in thread:" + Thread.currentThread().getName());break;case MESSAGE_FROM_WORK_THREAD:Log.d(TAG, "msg from work thread, handleMessage in thread:" + Thread.currentThread().getName());break;}}};Message msg = Message.obtain();msg.what = MESSAGE_FROM_MAIN_THREAD;mHandler.sendMessage(msg);new Thread(new Runnable() {@Overridepublic void run() {Message msg = Message.obtain();msg.what = MESSAGE_FROM_WORK_THREAD;mHandler.sendMessage(msg);}}).start();}@Overrideprotected void onDestroy() {super.onDestroy();mHandlerThread.quit();}
}

以上代码我们构建好HandlerThread以后,调用start()启动这个线程,然后分别在主线程/工作子线程发送消息,交给handler处理。
打印结果如下:

Test-Handler-Thread﹕ msg from main thread, handleMessage in thread:Handler-Thread
Test-Handler-Thread﹕ msg from work thread, handleMessage in thread:Handler-Thread

由此可见,不管是从那个线程发送的消息,handler都会统一在HandlerThread线程中执行。

注意: 在使用HandlerThread时,使用完毕以后,一定要注意调用mHandlerThread.quit(),否则HandlerThread的消息循环一直不会退出,这样会导致消息循环一直存在,这样HandlerThread就不会退出,这样,引用HandlerThread的activity也不会销毁。这样会导致内存泄漏。

3 HandlerThread源码分析

public class HandlerThread extends Thread {int mPriority;int mTid = -1;Looper mLooper;public HandlerThread(String name) {super(name);mPriority = Process.THREAD_PRIORITY_DEFAULT;}

以上代码可以看出,HandlerThread是一个线程。同时线程的优先级设置为默认优先级:Process.THREAD_PRIORITY_DEFAULT.

 protected void onLooperPrepared() {}@Overridepublic void run() {mTid = Process.myTid();Looper.prepare();synchronized (this) {mLooper = Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();Looper.loop();mTid = -1;}/*** This method returns the Looper associated with this thread. If this thread not been started* or for any reason is isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized.  * @return The looper.*/public Looper getLooper() {if (!isAlive()) {return null;}// If the thread has been started, wait until the looper has been created.synchronized (this) {while (isAlive() && mLooper == null) {try {wait();} catch (InterruptedException e) {}}}return mLooper;}

比较精彩的是这里run()以及getLooper()方法的设计。分析这段代码之前,我们要明白HandlerThread的使命:它是一个线程,帮我们自动建立好消息循环。OK,牢记这个使命这段代码就比较好懂了。有以下两个事实:
1)由于HandlerThread会和Handler联合起来使用,Handler会通过HandlerThread的getLooper()获取looper;
2)HandlerThread作为一个线程,要启动必须调用start()方法,start()方法调用以后,CPU调度线程以后,会自行run()方法。
run()方法的执行和getLooper()方法的调用是异步的。不管谁最先被调用,必须保证在调用getLooper()的时候,looper已经被初始化,否则就要等待looper被初始化。OK,明白这些隐含的规则以后,我们再来看代码实现。
run()方法中,会首先调用Looper.prepare(),然后执行looper的初始化,这里需要同步。基于前面的分析,run()和getLooper()调用时机异步,所以run()执行的时候,一旦looper初始化,就必须调用notifyAll(),通知被getLooper()阻塞的线程继续执行。
同时在getLooper()中,获取looper时,也必须同步,如果发现looper没有初始化,就wait()阻塞等待looper初始化完毕。
一个小的注意点: 从以上分析可知,一旦HandlerThread的run()没有执行,而先调用了getLooper(),那么调用getLooper()的线程会阻塞等待HandlerThread的start()被调用来触发looper初始化。所以如果getLooper()在主线程调用,为了获取最优性能,最好先调用HandlerThread的start(),然后再去调用getLooper(),如果getLooper()被调用以后,过了很久拆掉用HandlerThread的start(),会或多或少的导致主线程被阻塞一段时间。

   public boolean quit() {Looper looper = getLooper();if (looper != null) {looper.quit();return true;}return false;}

最后quit()方法,其实就是调用looper的quit来退出消息循环。避免消息循环一直在。所以HandlerThread使用完毕以后,要调用quit方法,否则会有内存泄漏。

这篇关于Android进阶系列之2:HandlerThread详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

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

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

Python中Flask模板的使用与高级技巧详解

《Python中Flask模板的使用与高级技巧详解》在Web开发中,直接将HTML代码写在Python文件中会导致诸多问题,Flask内置了Jinja2模板引擎,完美解决了这些问题,下面我们就来看看F... 目录一、模板渲染基础1.1 为什么需要模板引擎1.2 第一个模板渲染示例1.3 模板渲染原理二、模板

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

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

Redis中6种缓存更新策略详解

《Redis中6种缓存更新策略详解》Redis作为一款高性能的内存数据库,已经成为缓存层的首选解决方案,然而,使用缓存时最大的挑战在于保证缓存数据与底层数据源的一致性,本文将介绍Redis中6种缓存更... 目录引言策略一:Cache-Aside(旁路缓存)策略工作原理代码示例优缺点分析适用场景策略二:Re

Android开发环境配置避坑指南

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

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

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

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

MySQL数据库约束深入详解

《MySQL数据库约束深入详解》:本文主要介绍MySQL数据库约束,在MySQL数据库中,约束是用来限制进入表中的数据类型的一种技术,通过使用约束,可以确保数据的准确性、完整性和可靠性,需要的朋友... 目录一、数据库约束的概念二、约束类型三、NOT NULL 非空约束四、DEFAULT 默认值约束五、UN

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

MySQL中的分组和多表连接详解

《MySQL中的分组和多表连接详解》:本文主要介绍MySQL中的分组和多表连接的相关操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录mysql中的分组和多表连接一、MySQL的分组(group javascriptby )二、多表连接(表连接会产生大量的数据垃圾)MySQL中的