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

相关文章

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

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

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

SpringBoot整合mybatisPlus实现批量插入并获取ID详解

《SpringBoot整合mybatisPlus实现批量插入并获取ID详解》这篇文章主要为大家详细介绍了SpringBoot如何整合mybatisPlus实现批量插入并获取ID,文中的示例代码讲解详细... 目录【1】saveBATch(一万条数据总耗时:2478ms)【2】集合方式foreach(一万条数

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰

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

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