0%

Android开发:在后台服务中运行-创建后台服务

翻自:http://developer.android.com/training/run-background-service/create-service.html IntentService提供了在单个后台线程运行操作的简单结构。这允许它操作耗时操作,而不影响UI响应。同样,IntentService也不影响UI生命周期事件,所以,它在某些可能关闭AsyncTask的情况下,仍会继续运行(实测在Activity的onDestory里写AsyncTask无法运行)。 IntentService有如下限制:

  • 它不能直接影响UI。要把结果反映给UI,需要发给Activity
  • 工作请求会顺序运行。如果一个操作未结束,后面发送的操作必须等它结束(单线程)
  • IntentService里运行的操作无法被中断

然而,在大多数情况下,IntentService是简单后台任务的首选方式。 本节展示了如何创建IntentService的子类,如何创建onHandleIntent()回调,如何在AndroidManifest.xml声明IntentService。

创建IntentService

定义一个IntentService的子类,覆盖onHandleIntent()方法:

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里,应该避免覆盖这些回调。

在AndroidManifest.xml里定义IntentService

IntentService也是Service),需要在AndroidManifest.xml里注册。

    <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的类名。 注意:节点不能包含intent filter。发送工作请求的Activity使用明确的Intent,会指定哪个IntentService。这也意味着,只有同一个app里的组件,或者另一个有相同user id的应用才能访问IntentService。 现在你有了基础的IntentService类,可以用Intent对象发送工作请求。怎么发,下节讲。