0%

Android开发:在后台服务中运行-发送工作请求给后台服务

上节讲了如何创建IntentService。本节讲如何通过发送Intent触发IntentService执行操作。Intent可以包含任意数据。你可以在Activity或Fragment的任意位置发送Intent给IntentService。

创建发送工作请求传给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实现。