Android知识巩固--IntentService详解(消息机制的优秀实践)

本文主要是介绍Android知识巩固--IntentService详解(消息机制的优秀实践),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

为什么需要IntentService?

我们都知道Service是负责在后台处理比较耗时的操作的。但实际上Service也是运行在主线程中的。在我们需要在Service中开启子线程来执行我们的耗时操作。
一个使用Service的案例:

public class MyService extends Service {@Nullable@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {super.onCreate();Log.w("TAG", "Service Thread:"+Thread.currentThread().getId() + ":" + Thread.currentThread().getName());new Thread(new Runnable() {@Overridepublic void run() {//执行耗时的操作Log.w("TAG","Sub Thread:"+Thread.currentThread().getId() + ":" + Thread.currentThread().getName());}}).start();}
}

上面的Log打印如下

4510-4510/com.example.baronli.test W/TAG: Service Thread:1:main
4510-4566/com.example.baronli.test W/TAG: Sub Thread:181:Thread-4

表明Service的onCreate回调方法确实是运行在主线程中。
我们需要在Service中另外开启子线程执行我们的耗时任务。

IntentService使用

IntentService是则是对子线程进行了封装,提供了onHandleIntent()方法,onHandleIntent中的操作默认在子线程中执行

public class MyIntentService extends IntentService {public MyIntentService() {super("MyIntentService");Log.w("TAG", "MyIntentService Thread:" + Thread.currentThread().getId() + ":" + Thread.currentThread().getName());}@Overrideprotected void onHandleIntent(@Nullable Intent intent) {Log.w("TAG", "onHandleIntent Thread:" + Thread.currentThread().getId() + ":" + Thread.currentThread().getName());}
}
4510-4510/com.example.baronli.test W/TAG: MyIntentService Thread:1:main
4510-4567/com.example.baronli.test W/TAG: onHandleIntent Thread:182:IntentService[MyIntentService]

通过上面的Log我们可以发现IntentService其实本省的创建等操作也是在主线程中的,而onHandleIntent()方法中的代码则是在子线程中运行。这样就非常方便,我们只需要重写onHandleIntent()方法,在其中写我们的耗时操作就能够实现异步操作了。
注意
IntentService在执行完onHandleIntent()方法中的操作后会自动停止,不需要我们停止(自动调用stopSelf(msg.arg1);)

IntentService是串行执行,多个任务会进行排列,上一个执行完成后执行下一个。
如果多次调用startService()?

IntentService实现原理

IntentService实际上是利用Android的消息机制实现的,就是我们非常熟悉的Handler。
下面我们针对其源发分析一下(源码比较简单)

public abstract class IntentService extends Service {private volatile Looper mServiceLooper;private volatile ServiceHandler mServiceHandler;private String mName;private boolean mRedelivery;private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {onHandleIntent((Intent)msg.obj);stopSelf(msg.arg1);}}public IntentService(String name) {super();mName = name;}public void setIntentRedelivery(boolean enabled) {mRedelivery = enabled;}@Overridepublic void onCreate() {super.onCreate();HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");thread.start();mServiceLooper = thread.getLooper();mServiceHandler = new ServiceHandler(mServiceLooper);}@Overridepublic void onStart(@Nullable Intent intent, int startId) {Message msg = mServiceHandler.obtainMessage();msg.arg1 = startId;msg.obj = intent;mServiceHandler.sendMessage(msg);}@Overridepublic void onDestroy() {mServiceLooper.quit();}@Override@Nullablepublic IBinder onBind(Intent intent) {return null;}@WorkerThreadprotected abstract void onHandleIntent(@Nullable Intent intent);
}

我们重点看一下ServiceHandler的实现

 private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {//此处与我们一般在Activity的写法不同,此处Looper传入的事子线程中的Looper,我们在Activity中并没有此步骤,实质是默认采用的当前Activity所在的主线程的Looper,此处传过来的事子线程的Looper,则super(looper);}@Overridepublic void handleMessage(Message msg) {onHandleIntent((Intent)msg.obj);stopSelf(msg.arg1);}}

其实IntentService原理就是实例一个HandlerService,然后每次调用onStartCommand(会回调onStart)的时候给发送一个消息(Message)然后就会在子线程中回调 onHandleIntent((Intent)msg.obj);之后还会调 stopSelf(msg.arg1);

这篇关于Android知识巩固--IntentService详解(消息机制的优秀实践)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

C#读写文本文件的多种方式详解

《C#读写文本文件的多种方式详解》这篇文章主要为大家详细介绍了C#中各种常用的文件读写方式,包括文本文件,二进制文件、CSV文件、JSON文件等,有需要的小伙伴可以参考一下... 目录一、文本文件读写1. 使用 File 类的静态方法2. 使用 StreamReader 和 StreamWriter二、二进