创建后台服务

2018-08-15  本文已影响2人  鹿小纯0831

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

IntentService有一些限制:

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

本课程向您展示如何创建自己的IntentService子类。 本课程还向您展示了如何在onHandleIntent()上创建所需的回调方法。 最后,课程描述了如何在清单文件中定义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
        ...
    }
}

请注意,IntentService会自动调用常规Service组件的其他回调,例如onStartCommand()。 在IntentService中,您应该避免覆盖这些回调。

要了解有关创建IntentService的更多信息,请参阅扩展IntentService类。

二、在清单中定义intent服务

IntentService还需要应用程序清单中的条目。

    <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的其他应用程序才能访问该服务。

上一篇 下一篇

猜你喜欢

热点阅读