Android源码分析之HandlerThread
HandlerThread是一种特殊的Thread,也就是有Looper的thread,既然有looper的话,那我们就可以用此looper来
创建一个Handler,从而实现和它的交互,比如你可以通过与它关联的Handler对象在UI线程中发消息给它处理。HandlerThread
一般可以用来执行某些background的操作,比如读写文件(在此HandlerThread而非UI线程中)。既然还是一个Thread,那么
和一般的Thread一样,也要通过调用其start()方法来启动它。它只是Android替我们封装的一个Helper类,其源码相当简洁,我们
下面来看看,很简单。
和以往一样,我们先来看看字段和ctor:
int mPriority; // 线程优先级
int mTid = -1; // 线程id
Looper mLooper; // 与线程关联的Looper public HandlerThread(String name) { // 提供个名字,方便debug
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT; // 没提供,则使用默认优先级
} /**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority; // 使用用户提供的优先级,基于linux优先级,取值在[-20,19]之间
}
代码很简单,相关的分析都直接写在代码的注释里了,值得注意的是这里的priority是基于linux的优先级的,而不是Java Thread
类里的MIN_PRIORITY,NORM_PRIORITY,MAX_PRIORITY之类,请注意区分(其实认真阅读方法的doc即可)。
接下来看看此类的关键3个方法:
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() { // callback方法,如果你愿意可以Override放自己的逻辑;其在loop开始前执行
} @Override
public void run() {
mTid = Process.myTid();
Looper.prepare(); // 此方法我们前面介绍过,会创建与线程关联的Looper对象
synchronized (this) { // 进入同步块,当mLooper变的可用的使用,调用notifyAll通知其他可能block在当前对象上的线程
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority); // 设置线程优先级
onLooperPrepared(); // 调用回调函数
Looper.loop(); // 开始loop
mTid = -1; // reset为invalid值
} /**
* 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()) { // 如果线程不是在alive状态则直接返回null,有可能是你忘记调start方法了。。。
return null;
} // If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) { // 进入同步块,当条件不满足时无限等待,
try { // 直到mLooper被设置成有效值了才退出while(当然也可能是线程状态不满足);
wait(); // run方法里的notifyAll就是用来唤醒这里的
} catch (InterruptedException e) { // 忽略InterruptedException
}
}
}
return mLooper; // 最后返回mLooper,此时可以保证是有效值了。
}
当你new一个HandlerThread的对象时记得调用其start()方法,然后你可以接着调用其getLooper()方法来new一个Handler对象,
最后你就可以利用此Handler对象来往HandlerThread发送消息来让它为你干活了。
最后来看2个退出HandlerThread的方法,其实对应的是Looper的2个退出方法:
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper(); // 注意这里是调用getLooper而不是直接使用mLooper,
if (looper != null) { // 因为mLooper可能还没初始化完成,而调用方法可以
looper.quit(); // 等待初始化完成。
return true;
}
return false;
} /**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
通过代码我们可以看到其内部都是delegate给了Looper对象,而Looper我们在前面也介绍过了,感兴趣的同学可以翻看前面的分析或者
查看这2个方法的doc,写的都很详细。
至此这个简单的Handy class就算分析完毕了。在实际的开发中,如果你只是要做某些后台的操作(短暂的,比如把某些设置文件load
到内存中),而不需要更新UI的话,那你可以优先使用HandlerThread而不是AsyncTask。
接下来准备分析下Android提供的数据存储机制SharedPreferences,敬请期待。。。
Android源码分析之HandlerThread的更多相关文章
- Android源码分析-全面理解Context
前言 Context在android中的作用不言而喻,当我们访问当前应用的资源,启动一个新的activity的时候都需要提供Context,而这个Context到底是什么呢,这个问题好像很好回答又好像 ...
- Android源码分析(六)-----蓝牙Bluetooth源码目录分析
一 :Bluetooth 的设置应用 packages\apps\Settings\src\com\android\settings\bluetooth* 蓝牙设置应用及设置参数,蓝牙状态,蓝牙设备等 ...
- Android源码分析(十七)----init.rc文件添加脚本代码
一:init.rc文件修改 开机后运行一次: chmod 777 /system/bin/bt_config.sh service bt_config /system/bin/bt_config.sh ...
- Android源码分析(十六)----adb shell 命令进行OTA升级
一: 进入shell命令界面 adb shell 二:创建目录/cache/recovery mkdir /cache/recovery 如果系统中已有此目录,则会提示已存在. 三: 修改文件夹权限 ...
- Android源码分析(十五)----GPS冷启动实现原理分析
一:原理分析 主要sendExtraCommand方法中传递两个参数, 根据如下源码可以知道第一个参数传递delete_aiding_data,第二个参数传递null即可. @Override pub ...
- Android源码分析(十四)----如何使用SharedPreferencce保存数据
一:SharedPreference如何使用 此文章只是提供一种数据保存的方式, 具体使用场景请根据需求情况自行调整. EditText添加saveData点击事件, 保存数据. diff --git ...
- Android源码分析(十三)----SystemUI下拉状态栏如何添加快捷开关
一:如何添加快捷开关 源码路径:frameworks/base/packages/SystemUI/res/values/config.xml 添加headset快捷开关,参考如下修改. Index: ...
- Android源码分析(十二)-----Android源码中如何自定义TextView实现滚动效果
一:如何自定义TextView实现滚动效果 继承TextView基类 重写构造方法 修改isFocused()方法,获取焦点. /* * Copyright (C) 2015 The Android ...
- Android源码分析(十一)-----Android源码中如何引用aar文件
一:aar文件如何引用 系统Settings中引用bidehelper-1.1.12.aar 文件为例 源码地址:packages/apps/Settings/Android.mk LOCAL_PAT ...
随机推荐
- 进阶学习js中的执行上下文
在js中的执行上下文,菜鸟入门基础 这篇文章中我们简单的讲解了js中的上下文,今天我们就更进一步的讲解js中的执行上下文. 1.当遇到变量名和函数名相同的问题. var a = 10; functio ...
- D3D的绘制
一.D3D中的绘制 顶点缓存和索引缓存:IDirect3DVertexBuffer9 IDirect3DIndexBuffer 使用这两缓存而不是用数组来存储数据的原因是,缓存可以被放置在显存中,进行 ...
- 【原创】C#搭建足球赛事资料库与预测平台(4) 比赛信息数据表设计
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源C#彩票数据资料库系列文章总目录:[目录]C#搭建足球赛事资料库与预测平台与彩票数据分析目录 本篇文章开始将逐步介 ...
- AEM - Adobe CMS 扒坑记之始
AEM是Adobe公司所出的商业内容管理系统,全称阿豆比体验管理系统(Adobe Experience Manager),其前身叫CQ,分别有CQ5 CQ6两个大版本.它提供了整套的网站内容管理系统解 ...
- iOS-项目搭建
一.目的:一个小的项目当然不需要这么费劲的搞,到时一个大的项目要是不好好设计一下的话,写到后面就不知道怎么分类或者命名了,搞的项目很乱.为了更好的对本项目的查看,修改和后期的维护.一个好的项目的搭建不 ...
- CSS程序思想
CSS的设计思想,比如:CSS预处理器.CSS对像(OOCSS).SMACSS.Atomic设计和OrganicCSS等 一.CSS预处理器最重要的功能: 1.连接: ...
- 使用VS2010开发Qt程序的一点经验
导读 相比于Qt Creator,我更喜欢用VS2010来进行开发.虽然启动时间相对较慢,但是VS下强大的快捷键和丰富的插件,以及使用多年的经验,都让我觉得在开发过程中得心应手.其中最重要的一点是,有 ...
- HTML5实现音频播放
Web 上的音频 直到现在,仍然不存在一项旨在网页上播放音频的标准. 今天,大多数音频是通过插件(比如 Flash)来播放的.然而,并非所有浏览器都拥有同样的插件. HTML5 规定了一种通过 aud ...
- 创业型互联网公司应该选择PHP, JavaEE还是.NET技术路线?
通常JavaEE和.NET被定义为构建大型在线系统,因为其支持面向对象设计,异步通讯,MVC等都相对比较完善,而PHP通常用于构建比较轻量的业务,例如SNS服务. 因为实施速度快,工程师社区规模大,开 ...
- where T : class的含义
public class Reflect<T> where T : class { 这是参数类型约束,指定T必须是Class类型. .NET支持的类型参数约束有以下五种:where T : ...