• IntentService 源码理解


    一、概述

            本篇文章讲解的是分析IntentService源码并使用,安卓API迭代更新的太快,IntentService已经在Android8.0 (API 26)之后就不推荐使用了,在Android API 30正式弃用,官方建议用JobIntentService 或 WorkManager替代,但它的实现源码和思想也值得再回味一下。读本篇文章之前,请移步笔者的另外一篇文章:

    HandlerThread源码理解_broadview_java的博客-CSDN博客 , 理解HandlerThread的用法后,对理解IntentService 也会事半功倍。

    二、IntentService是什么

    2.1 概述

            IntentService 继承了Service,并且它是一个抽象类,它又比普通的Service增加了额外的功能。那Google为什么要引入IntentService呢?

    1. 我们知道Service它是一个服务,是Android四大组件之一,它和应用程序处于同一个进程之中

    2. Service也不是一个线程,和线程完全没有关系,所以你在Service中直接处理耗时的任务,容易引起ANR。如果要做耗时任务,还必须要手动开启一个线程去处理任务。

    3. 从Service的生命周期管理角度来看,startService启动服务,当做完任务后,还需要调用stopService停止服务。

    但是 IntentService 就不需要考虑这么多,它既不需要去我们手动去开线程,也不需要我们做完任务后手动停止服务

    2.2 特征

    1. IntentService 会创建单独的work线程来处理所有的Intent请求,开发者无需处理多线程问题

    2. IntentService可用于执行后台耗时任务,当所有请求处理完成后,IntentService会自动停止

    3. IntentService是一个服务,四大组件之一,所以它的优先级肯定要比单独创建出来一个线程优先级要高,因此也不容易被系统kill掉,可以保证后台任务能完成。

    三、源码分析

    1. //IntentService首先是一个抽象类,类中只有一个abstarct抽象方法:onHandleIntent
    2. //所以我们需要重写onHandleIntent这个方法
    3. public abstract class IntentService extends Service {
    4. private volatile Looper mServiceLooper;
    5. @UnsupportedAppUsage
    6. private volatile ServiceHandler mServiceHandler;
    7. private String mName;
    8. private boolean mRedelivery;
    9. //内部ServiceHandler,用于线程间通信
    10. //这里是消息处理端,对应于 onStar()消息发送端
    11. private final class ServiceHandler extends Handler {
    12. public ServiceHandler(Looper looper) {
    13. super(looper);
    14. }
    15. @Override
    16. public void handleMessage(Message msg) {
    17. //此方法用于处理耗时逻辑任务
    18. onHandleIntent((Intent)msg.obj);
    19. //当所有任务执行完毕后,就停止服务
    20. stopSelf(msg.arg1);
    21. }
    22. }
    23. /**
    24. * Creates an IntentService. Invoked by your subclass's constructor.
    25. * 通过名称来创建IntentService
    26. * @param name Used to name the worker thread, important only for debugging.
    27. */
    28. public IntentService(String name) {
    29. super();
    30. mName = name;
    31. }
    32. /**
    33. * Sets intent redelivery preferences. Usually called from the constructor
    34. * with your preferred semantics.
    35. *
    36. *

      If enabled is true,

    37. * {@link #onStartCommand(Intent, int, int)} will return
    38. * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
    39. * {@link #onHandleIntent(Intent)} returns, the process will be restarted
    40. * and the intent redelivered. If multiple Intents have been sent, only
    41. * the most recent one is guaranteed to be redelivered.
    42. *
    43. *

      If enabled is false (the default),

    44. * {@link #onStartCommand(Intent, int, int)} will return
    45. * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
    46. * dies along with it.
    47. */
    48. public void setIntentRedelivery(boolean enabled) {
    49. mRedelivery = enabled;
    50. }
    51. @Override
    52. public void onCreate() {
    53. super.onCreate();
    54. //内部还是由 HandlerThread + Handler 来实现的
    55. HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    56. //HandlerThread在线程内部创建Looper和消息队列,并且在线程启动之后开启消息循环
    57. thread.start();
    58. //获取工作线程的Looper
    59. mServiceLooper = thread.getLooper();
    60. //创建ServiceHandler,绑定工作线程的Looper,这样子ServiceHandler就可以往消息队
    61. //中分发消息
    62. mServiceHandler = new ServiceHandler(mServiceLooper);
    63. }
    64. @Override
    65. public void onStart(@Nullable Intent intent, int startId) {
    66. Message msg = mServiceHandler.obtainMessage();
    67. msg.arg1 = startId;
    68. msg.obj = intent;
    69. //发送消息,添加到消息队列
    70. mServiceHandler.sendMessage(msg);
    71. }
    72. /**
    73. * You should not override this method for your IntentService. Instead,
    74. * override {@link #onHandleIntent}, which the system calls when the IntentService
    75. * receives a start request.
    76. * @see android.app.Service#onStartCommand
    77. 自定义的IntentService 可以不用复写 onStartCommand方法,但是一定要复写onHandleIntent方法
    78. */
    79. @Override
    80. public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    81. //调用onStart(intent, startId)方法
    82. onStart(intent, startId);
    83. return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    84. }
    85. @Override
    86. public void onDestroy() {
    87. mServiceLooper.quit();
    88. }
    89. /**
    90. * Unless you provide binding for your service, you don't need to implement this
    91. * method, because the default implementation returns null.
    92. * @see android.app.Service#onBind
    93. */
    94. @Override
    95. @Nullable
    96. public IBinder onBind(Intent intent) {
    97. return null;
    98. }
    99. /**
    100. * This method is invoked on the worker thread with a request to process.
    101. * Only one Intent is processed at a time, but the processing happens on a
    102. * worker thread that runs independently from other application logic.
    103. * So, if this code takes a long time, it will hold up other requests to
    104. * the same IntentService, but it will not hold up anything else.
    105. * When all requests have been handled, the IntentService stops itself,
    106. * so you should not call {@link #stopSelf}.
    107. *
    108. * @param intent The value passed to {@link
    109. * android.content.Context#startService(Intent)}.
    110. * This may be null if the service is being restarted after
    111. * its process has gone away; see
    112. * {@link android.app.Service#onStartCommand}
    113. * for details.
    114. */
    115. //在自己的IntentService中重写此方法
    116. @WorkerThread
    117. protected abstract void onHandleIntent(@Nullable Intent intent);
    118. }

    3.1 onCreate()方法

    1. @Override
    2. public void onCreate() {
    3. super.onCreate();
    4. //内部还是由 HandlerThread + Handler 来实现的
    5. HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    6. //HandlerThread在线程内部创建Looper和消息队列,并且在线程启动之后开启消息循环
    7. thread.start();
    8. //获取工作线程的Looper
    9. mServiceLooper = thread.getLooper();
    10. //创建ServiceHandler,绑定工作线程的Looper,这样子ServiceHandler就可以往消息队
    11. //中分发消息
    12. mServiceHandler = new ServiceHandler(mServiceLooper);
    13. }

    参考之前写的HandlerThread源码理解,我们知道 IntentService 其实内部封装了 HandlerThread + Handler ,这也解释了它可以用来执行后台任务,而不会阻塞UI线程引起ANR。

    3.2 onStartCommand()方法

    1. @Override
    2. public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    3. //调用onStart(intent, startId)方法
    4. onStart(intent, startId);
    5. return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    6. }

    补充一下基础知识,在Service生命周期中,当第一次用startService方法启动服务时回调:

    onCreate()---->onStartCommand()  ; 如果再启动该正在运行的服务,它不会再走onCreate()

    只会走onStartCommand() ,源码中接着会调用onStart(intent, startId) 方法,这里也可以延伸一下,我们在实际应用中,就可以多次调用startService()方法来执行多项后台任务,IntentService也会多次调用 onStart(intent, startId)方法 ,我们来看看此方法

    3.3  onStart(@Nullable Intent intent, int startId) 方法

    1. @Override
    2. public void onStart(@Nullable Intent intent, int startId) {
    3. Message msg = mServiceHandler.obtainMessage();
    4. msg.arg1 = startId;
    5. msg.obj = intent;
    6. //发送消息,添加到消息队列
    7. mServiceHandler.sendMessage(msg);
    8. }

    也就是每调用一下此方法,就会封装一个不同 startID 的Message对象,然后通过mServiceHandler分发到工作线程中去处理,由于HandlerThread 是单线程工作,所以这些任务就需要排队一个一个的处理,待处理完毕,就停止服务,这也是设计巧妙的地方,避免了多次创建IntentService.

    3.4 onDestory()方法

    1. @Override
    2. public void onDestroy() {
    3. mServiceLooper.quit();
    4. }

       Looper消息轮询器退出

    3.5 stopSelf(int startId)方法

            此方法不同于Service的stopSelf()方法,当onHandlerIntent方法执行结束后,IntentService会通过stopSelf(int startId)方法来尝试停止服务。这里之所以采用stopSelf(int startId)而不是stopSelf()方法,那是因为stopSelf()会立即停止运行的服务,而这个时候可能还有其他消息未处理,stopSelf(int startId)则会等待所有的消息都处理完毕后才会停止服务。一般来说stopSelf(int startId)在尝试停止服务之前会判断最近启动的服务次数是否和startId相等,如果相等就立刻停止服务,不相等则不停止服务,这个策略可以从 AMS 的 public boolean stopServiceToken(ComponentName className, IBinder token, int startId) 这个方法中去查证。

    四、实例演示

    首先我在IntentService源码中加两句打印log:

    然后编译替换 framework.jar 

    下面是Demo代码:

    1. public class MainActivity extends AppCompatActivity {
    2. private Button mStartButton;
    3. private Button mStopButton;
    4. @Override
    5. protected void onCreate(Bundle savedInstanceState) {
    6. super.onCreate(savedInstanceState);
    7. setContentView(R.layout.activity_main);
    8. mStartButton = findViewById(R.id.service_start);
    9. Intent intent = new Intent(this, MyIntentService.class);
    10. mStartButton.setOnClickListener(new View.OnClickListener() {
    11. @Override
    12. public void onClick(View v) {
    13. intent.putExtra("task_id", "任务1");
    14. startService(intent);
    15. intent.putExtra("task_id", "任务2");
    16. startService(intent);
    17. intent.putExtra("task_id", "任务3");
    18. startService(intent);
    19. }
    20. });
    21. }
    22. }
    1. public class MyIntentService extends IntentService {
    2. public MyIntentService() {
    3. super("myIntentService");
    4. }
    5. @Override
    6. public void onCreate() {
    7. super.onCreate();
    8. Log.d("test", "=====MyIntentService====onCreate====");
    9. }
    10. @Override
    11. protected void onHandleIntent(@Nullable Intent intent) {
    12. String taskName = intent.getStringExtra("task_id");
    13. Log.e("test", "mServiceHandler 处理线程名称:" + Thread.currentThread().getName());
    14. Log.d("test", "======通过线程睡眠10秒模拟耗时任务==="+ taskName + "====start======");
    15. try {
    16. Thread.sleep(10000);
    17. } catch (InterruptedException e) {
    18. }
    19. Log.d("test", "======"+ taskName + "====end======");
    20. }
    21. @Override
    22. public void onDestroy() {
    23. Log.e("test", "=====MyIntentService====onDestroy====");
    24. super.onDestroy();
    25. }

    运行打印log如下:

     通过上述log分析,我们可以得出如下结论:

    1. 当执行多个耗时任务时,它的工作模式是单服务(一个IntentService),单线程顺序执行任务(任务1执行--->  执行任务2 ----> 执行任务3 )----->退出服务

    2. 睡眠10秒,模拟耗时任务,也不会引起ANR,说明是在子线程中执行任务,也和源码中IntentService 内部实现是HandlerThread 可以对应上。

    我们把源码中IntentService加的log去掉,只打印任务执行相关的log,也更加清楚其执行过程:

    1. 11-18 18:06:20.251 3085 3085 D ok : =====MyIntentService====onCreate====
    2. 11-18 18:06:20.253 3085 3159 D ok : ======通过线程睡眠10秒模拟耗时任务===任务1====start======
    3. 11-18 18:06:30.253 3085 3159 D ok : ======任务1====end======
    4. 11-18 18:06:30.255 3085 3159 D ok : ======通过线程睡眠10秒模拟耗时任务===任务2====start======
    5. 11-18 18:06:40.255 3085 3159 D ok : ======任务2====end======
    6. 11-18 18:06:40.257 3085 3159 D ok : ======通过线程睡眠10秒模拟耗时任务===任务3====start======
    7. 11-18 18:06:50.257 3085 3159 D ok : ======任务3====end======
    8. 11-18 18:06:50.261 3085 3085 E ok : =====MyIntentService====onDestroy====

     好了,到这里就应该对IntentService的使用差不多明白了,多打印log调试理解的更深一点。

  • 相关阅读:
    通过vue ui方式构建vue+electron项目
    SQL DDL DML
    命令模式-
    Java版分布式微服务云开发架构 Spring Cloud+Spring Boot+Mybatis 电子招标采购系统功能清单
    【AI视野·今日Robot 机器人论文速览 第五十二期】Wed, 11 Oct 2023
    I 用c l 栈与队列的相互实现
    最新JMeter面试题,紧扣面试实际要求,看完拿下20K
    Node.js | 你不知道的 express 路由使用技巧
    HTTPDNS
    移动端使用vantUI的list组件,多个tab项来回切换时,列表加载多次导致数据无法正常展示
  • 原文地址:https://blog.csdn.net/u012514113/article/details/127919663