注:
IntentService类在API级别30(Android R?)中被弃用。 IntentService受Android 8.0(API级别26)施加的所有后台执行限制的约束。推荐使用{@link android.support.v4.app.JobIntentService},它在Android 8或更高版本上运行时使用Job而不是Service。
IntentService介绍
IntentService是Service的扩展,可按需处理异步请求(请求一般以intent表示), client端通过调用Context.startService(Intent)发送请求, 然后service将被启动,使用工作线程依次处理intent,当所有intent处理完毕,则停止service
这种“工作队列处理器”模式通常用于为主线程减负,将耗时的可能block主线程的工作放到工作线程去处理。IntentService类的存在是为了简化这种模式。使用IntentService,需要继承IntentService,同时实现onHandleIntent(android.content.Intent)方法。IntentService接收从client端发过来的intent,将其作为消息发给工作线程去处理消息。
所有请求都在一个工作线程上处理——它们可能很耗时(根据需要)(但不会阻塞应用程序的main loop),但一次只处理一个请求。
IntentService代码
定义:
/**
* IntentService is a base class for {@link Service}s that handle asynchronous
* requests (expressed as {@link Intent}s) on demand. Clients send requests
* through {@link android.content.Context#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.
*
* <p>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 {@link #onHandleIntent(Intent)}. IntentService
* will receive the Intents, launch a worker thread, and stop the service as
* appropriate.
*
* <p>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.
*
* <p class="note"><b>Note:</b> IntentService is subject to all the
* <a href="/preview/features/background.html">background execution limits</a>
* imposed with Android 8.0 (API level 26). In most cases, you are better off
* using {@link android.support.v4.app.JobIntentService}, which uses jobs
* instead of services when running on Android 8.0 or higher.
* </p>
*
* @see android.support.v4.app.JobIntentService
* @see android.os.