IntentService提供了在单个后台线程运行操作的简单结构。这允许它操作耗时操作,而不影响UI响应。同样,IntentService也不影响UI生命周期事件,所以,它在某些可能关闭AsyncTask的情况下,仍会继续运行(实测在Activity的onDestory里写AsyncTask无法运行)。 IntentService有如下限制: 1.它不能直接影响UI。要把结果反映给UI,需要发给Activity 2.工作请求会顺序运行。如果一个操作未结束,后面发送的操作必须等它结束(单线程) 3.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的类名。 注意:<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实现。请参考此文:http://www.jb51.net/article/51548.htm