IntentService
类提供一个简单的运行结构, 执行单个后台线程上的操作这样,它可以处理长时间运行的操作 而不会影响用户界面的响应速度。此外, IntentService
不受大多数界面生命周期事件的影响,因此 在会导致AsyncTask
关闭的情况下继续运行
IntentService
有一些限制:
- 它无法直接与您的界面互动。为了在界面中显示结果 必须将其发送到
Activity
。 - 工作请求依序运行。如果某项操作是在
IntentService
,而您向它发送了另一个请求,则该请求会等到 第一个操作完成时 - 在
IntentService
上运行的操作无法中断。
不过,在大多数情况下,最好使用 IntentService
来执行 简单的后台操作
本指南将向您介绍如何执行以下操作:
- 创建您自己的
IntentService
子类。 - 创建所需的回调方法
onHandleIntent()
。 - 定义
IntentService
。
处理传入的 intent
如需为您的应用创建 IntentService
组件,请定义一个类 扩展 IntentService
,并在其中定义一个方法, 会替换 onHandleIntent()
。例如:
Kotlin
class RSSPullService : IntentService(RSSPullService::class.simpleName) override fun onHandleIntent(workIntent: Intent) { // Gets data from the incoming Intent val dataString = workIntent.dataString ... // Do work here, based on the contents of dataString ... } }
Java
public class RSSPullService extends IntentService { @Override protected void onHandleIntent(Intent workIntent) { // Gets data from the incoming Intent String dataString = workIntent.getDataString(); ... // Do work here, based on the contents of dataString ... } }
请注意,常规 Service
组件的其他回调,例如 由系统自动调用 onStartCommand()
IntentService
。在 IntentService
中,您应该避免 替换这些回调。
如需详细了解如何创建 IntentService
,请参阅扩展 IntentService 类。
在清单中定义 intent 服务
IntentService
还需要应用清单中的条目。 提供此条目作为 <service>
元素,该元素是 <application>
元素:
<application android:icon="@drawable/icon" android:label="@string/app_name"> ... <!-- Because android:exported is set to "false", the service is only available to this app. --> <service android:name=".RSSPullService" android:exported="false"/> ... </application>
android:name
属性用于指定 IntentService
。
请注意, <service>
元素不包含 intent 过滤器。通过 向服务发送工作请求的 Activity
使用 显式 Intent
,因此无需过滤器。这也 则意味着只有同一应用或其他应用中的组件 可以访问该服务。
现在,您已经有了基本的 IntentService
类,可以发送工作请求了 并使用 Intent
对象将其添加到其中。构建这些对象的流程 以及如何将其发送到您的 IntentService
将工作请求发送到后台服务。