Android中使用IntentService创建后台服务实例

2019-12-10 20:01:54王振洲

            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 filter。发送工作请求的Activity使用明确的Intent,会指定哪个IntentService。这也意味着,只有同一个app里的组件,或者另一个有相同user id的应用才能访问IntentService。

现在你有了基础的IntentService类,可以用Intent对象发送工作请求。

创建发送工作请求传给IntentService

创建一个明确的Intent,添加需要的数据,调用startService()发送给IntentService

 

复制代码 /*
 * Creates a new Intent to start the RSSPullService
 * IntentService. Passes a URI in the
 * Intent's "data" field.
 */
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));
//Call startService() 
// Starts the IntentService
getActivity().startService(mServiceIntent);

 

提示:可以在Activity or Fragment的任意位置发送工作请求。如果你需要先取到用户输入,你可以在点击事件或类似手势的回调方法里发送工作请求。

一旦调用了startService(),IntentService会在onHandleIntent()工作,完了结束自身。

下一步是报告结果给原来的Activity或Fragment,下节讲如何用BroadcastReceiver实现。