创建后台服务

IntentService 类为在单个后台线程上运行操作提供了一个简单明了的结构。这样,它可以在不影响界面的响应速度的情况下处理长时间运行的操作。此外,IntentService 不受大多数界面生命周期事件的影响,因此它能够在会关闭 AsyncTask 的情况下继续运行

IntentService 有一些限制:

  • 它无法直接与您的界面互动。如需在界面中显示其结果,您必须将其发送到 Activity
  • 工作请求依序运行。如果某个操作在 IntentService 中运行,并且您向其发送了另一个请求,则该请求会等待第一个操作完成。
  • IntentService 上运行的操作无法中断。

不过,在大多数情况下,IntentService 是执行简单后台操作的首选方式。

本指南介绍了如何执行以下操作:

处理传入的 intent

如需为您的应用创建 IntentService 组件,请定义一个扩展 IntentService 的类,并在其中定义替换 onHandleIntent() 的方法。例如:

KotlinJava
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
       
...
   
}
}
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 的过程。