IntentService源码分析

Posted Android开发中文站

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IntentService源码分析相关的知识,希望对你有一定的参考价值。

1.IntentService用来干什么?

一般情况下,service是在主线程中运行的,这样如果处理耗时操作会造成ANR的问题,但是很多场景下我们需要用service进行耗时操作,此时就需要一种新的机制,于是便引进了IntentService的概念。


先看一下官方的说法吧


IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread — they may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.


总结一下,就是IntentService为了符合下面需求的场景。


  • 处理异步请求

  • 处理完请求后自动结束


2.怎么实现的上述需求?

2.1 异步处理耗时任务


先看一眼IntentService的成员:


(c)2006-2024 SYSTEM All Rights Reserved IT常识