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
也需要一个条目。将此条目作为 <application>
元素的子元素,以 <service>
元素的形式提供:
<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
,因此不需要过滤器。这也意味着只有同一应用中的组件或具有相同用户 ID 的其他应用才能访问该服务。
现在您已经有了基本的 IntentService
类,您可以使用 Intent
对象向其发送工作请求。构建这些对象并将它们发送到您的 IntentService
的过程在向后台服务发送工作请求中进行了描述。