IntentService 使用与源码解析

2023-12-05 14:08

本文主要是介绍IntentService 使用与源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

IntentService 使用与源码解析

IntentService 这兄弟用的地方也蛮多,用起来也蛮顺手, 而且用过不用太操心是否将其关闭。 之前在介绍Handler消息机制一文中简单介绍其工作原理。 本文就着重IntentService进行解析。

本文主要分六部分展开:

  1. IntentService的介绍
  2. IntentService的使用
  3. IntentService的源码解析
  4. IntentService的常见问题
  5. 总结
  6. 参考资料

1. IntentService的介绍

这么说吧如果有一个任务,可以分成很多个子任务,需要按照顺序来完成,如果需要放到一个服务中完成,那么使用IntentService是最好的选择。

一般情况下我们所使用的Service是运行在主线程当中的,所以在service里面编写耗时的操作代码,则会卡主线程会ANR。为了解决这样的问题,谷歌引入了IntentService.

IntentService是自己维护了一个线程,来执行耗时的操作,然后里面封装了HandlerThread,能够方便在子线程创建Handler。

IntentService是继承自Service用来处理异步请求的一个基类,客户端startService发送请求,IntentService就被启动,然后会在一个工作线程中处理传递过来的Intent,当任务结束后就会自动停止服务。

2. IntentService的使用

IntentService的使用十分简单,分为下面几个步骤:

  • 新建子类继承IntentService,在AndroidManifest注册该Service, 复写onHandleIntent方法并在onHandleintent方法中进行异步操作
  • 一般在Activity中调用IntentService,与使用普通Service类似,不过不要使用绑定方式,而要使用startService启动,并在Intent中放入相应的数据
  • 使用Handler或者本地广播等手段将onHandleIntent异步执行结果传给主线程
  • 主线程获取到异步操作结果并对其进行处理和展示等等

具体的使用方法就不粘贴了, 网上代码一搜一大把。

3. IntentService的源码解析

源码解析, 鉴于 IntentService 一共也没多少行,索性都粘出来 。

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);}}/*** Creates an IntentService.  Invoked by your subclass's constructor.** @param name Used to name the worker thread, important only for debugging.*/public IntentService(String name) {super();mName = name;}/*** Sets intent redelivery preferences.  Usually called from the constructor* with your preferred semantics.** <p>If enabled is true,* {@link #onStartCommand(Intent, int, int)} will return* {@link Service#START_REDELIVER_INTENT}, so if this process dies before* {@link #onHandleIntent(Intent)} returns, the process will be restarted* and the intent redelivered.  If multiple Intents have been sent, only* the most recent one is guaranteed to be redelivered.** <p>If enabled is false (the default),* {@link #onStartCommand(Intent, int, int)} will return* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent* dies along with it.*从字面理解是设置intent重投递。如果设置为true,onStartCommand(Intent, int, int)将会返回START_REDELIVER_INTENT,如果onHandleIntent(Intent)返回之前进程死掉了,那么进程将会重新启动,intent重新投递,如果有大量的intent投递了,那么只保证最近的intent会被重投递。*/public void setIntentRedelivery(boolean enabled) {mRedelivery = enabled;}/// Service的onCreate 被调用时 即创建 handlerThread  , 将HandlerThread的Looper 与ServiceHandler关联。 至此 ServiceHandler 与异步的子线程HandlerThread 便绑在了一起。 也为后面的有序执行任务做下了铺垫, 可谓设计精妙。 @Overridepublic void onCreate() {// TODO: It would be nice to have an option to hold a partial wakelock// during processing, and to have a static startService(Context, Intent)// method that would launch the service & hand off a wakelock.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);}/*** You should not override this method for your IntentService. Instead,* override {@link #onHandleIntent}, which the system calls when the IntentService* receives a start request.* @see android.app.Service#onStartCommand*  启动 除了第一次 调用onCreate 方法 关联HandlerThread 与ServiceHandler . 其后 再次调用 则会调用onStartCommand 方法 。该方法 内部会调用onStart方法 。 而同时会把startID传递进入Message  ,将Intent 作为 message之obj  包装后 发送 。 IntentService 是一种non-sticky 服务,non-sticky 服务在服务自己认为完成任务时停止,为了获得non-sticky 服务,应返回 START_REDELIVER_INTENT 或者 START_NOT_STICKY,而二者的区别则是如果系统需要在服务完成任务之前关闭它,则服务的具体表现不同,START_NOT_STICKY会被关闭,而START_REDELIVER_INTENT则会在系统可用资源不吃紧时,尝试再次启动。*/@Overridepublic int onStartCommand(@Nullable Intent intent, int flags, int startId) {onStart(intent, startId);return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;}/// Looper  quit 之后 该Looper便停止 循环。 同时Service销毁。 @Overridepublic void onDestroy() {mServiceLooper.quit();}/*** Unless you provide binding for your service, you don't need to implement this* method, because the default implementation returns null.* @see android.app.Service#onBind*/@Override@Nullablepublic IBinder onBind(Intent intent) {return null;}/*** This method is invoked on the worker thread with a request to process.* Only one Intent is processed at a time, but the processing happens on a* worker thread that runs independently from other application logic.* So, if this code takes a long time, it will hold up other requests to* the same IntentService, but it will not hold up anything else.* When all requests have been handled, the IntentService stops itself,* so you should not call {@link #stopSelf}.** @param intent The value passed to {@link*               android.content.Context#startService(Intent)}.*               This may be null if the service is being restarted after*               its process has gone away; see*               {@link android.app.Service#onStartCommand}*               for details.当在onStart方法中,通过sendMessage方法将Message放入到Handler所关联的消息队列中后,Handler所关联的Looper对象会从消息队列中取出一个Message,然后将其传入Handler的handleMessage方法中,在handleMessage方法中首先通过Message的obj获取到了原始的Intent对象,然后将其作为参数传给了onHandleIntent方法让其执行。handleMessage方法是运行在HandlerThread的,所以onHandleIntent也是运行在工作线程中的。在执行完了onHandleIntent之后,我们需要调用stopSelf(startId)声明某个job完成了。当所有job完成的时候,Android就会回调onDestroy方法,销毁IntentService。*/@WorkerThread  ///  该方法为工作线程  也就是再HandlerThread中被调用。 protected abstract void onHandleIntent(@Nullable Intent intent);
}

HandlerThread的源码解析就不再赘述了, 如有想要深入了解的可查看我的另一篇文章 Android Handler消息机制解析中的HandlerThread 部分。 算了再简单把注释粘一下。

public class HandlerThread extends Thread {//线程优先级int mPriority;int mTid = -1;Looper mLooper;public HandlerThread(String name) {super(name);mPriority = Process.THREAD_PRIORITY_DEFAULT;}public HandlerThread(String name, int priority) {super(name);mPriority = priority;}protected void onLooperPrepared() {}@Overridepublic void run() {//获取进程IDmTid = Process.myTid();//Loopr准备Looper.prepare();//创建Loopersynchronized (this) {mLooper = Looper.myLooper();//唤醒所有等待的线程notifyAll();}//设置线程优先级Process.setThreadPriority(mPriority);//在Looper循环时做一些准备工作onLooperPrepared();//开启循环Looper.loop();mTid = -1;}public Looper getLooper() {//如果线程已经消亡,就返回nullif (!isAlive()) {return null;}//如果线程已经创建了,就在此处停留等待Looper创建完成之后synchronized (this) {while (isAlive() && mLooper == null) {//等待线程被创建try {wait();} catch (InterruptedException e) {}}}return mLooper;}public boolean quit() {//获取looperLooper looper = getLooper();if (looper != null) {//退出looperlooper.quit();return true;}return false;}//安全退出//跟quit方法的唯一区别在于looper.quit()变成了looper.quitSafely()public boolean quitSafely() {Looper looper = getLooper();if (looper != null) {looper.quitSafely();return true;}return false;}/*** Returns the identifier of this thread. See Process.myTid().*/public int getThreadId() {return mTid;}
}

4. IntentService的常见问题

a. 如果启动IntentService多次,会出现什么情况呢?

IntentService多次被启动,那么onCreate()方法只会调用一次,所以只会创建一个工作线程。但是会调用多次onStartCommand方法,只是把消息加入消息队列中等待执行

b. 多次开启intentService,那为什么工作任务队列是顺序执行的?

当我们通过startService多次启动了IntentService,这会产生多个job,由于IntentService只持有一个工作线程,所以每次onHandleIntent只能处理一个job。面多多个job,IntentService会如何处理?处理方式是one-by-one,也就是一个一个按照先后顺序处理,先将intent1传入onHandleIntent,让其完成job1,然后将intent2传入onHandleIntent,让其完成job2…这样直至所有job完成,所以我们IntentService不能并行的执行多个job,只能一个一个的按照先后顺序完成,当所有job完成的时候IntentService就销毁了,会执行onDestroy回调方法。

5. 总结

IntentService的优点

  1. 它创建一个独立的工作线程来处理所有一个一个intent。
  2. 创建了一个工作队列,来逐个发送intent给onHandleIntent()
  3. 不需要主动调用stopSelf()来结束服务,因为源码里面自己实现了自动关闭。
  4. 默认实现了onBind()返回的null。
  5. 默认实现的onStartCommand()的目的是将intent插入到工作队列。

IntentService使用场景

  1. IntentService不需要我们自己去关闭Service,它自己会在任务完成之后自行关闭,不过每次只能处理一个任务,所以不适用于高并发,适用于请求数较少的情况。
    类似于APP的版本检测更新、 定位功能、同步通讯录、 笔记应用的笔记列表 资源同步以及 读取少量的IO操作。
  2. 推送Service 例如 阿里的推送Service就是 集成自IntentService 。
  3. 还可以将 应用的初始化, 例如MultiDex中dex的异步加载, 资源文件的异步加载等。

6. 参考资料

  • 一个例子带IntentService入门
  • Android Handler消息机制解析

这篇关于IntentService 使用与源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

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

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

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

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

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

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义