android 后台运行服务之发送工作请求给后台服务篇

来源:互联网 发布:java web远程调试 编辑:程序博客网 时间:2024/05/02 11:19

前一篇讲述了如何创建一个IntentService 类, 这里将继续讲述如何发送一个Intent 给IntentService触发运行某个操作。您可以发送包含可选数据的intent给intentService 去处理,可以在一个Activity 或者Fragment 如何地方发送一个intent 给一个IntentService。


2.创建和发送一个工作请求给IntentService


为了创建一个工作请求以及发送它给一个IntentService, 创建一个明确的Intent, 并添加工作请求数据给它,然后调用startService() 发送它给IntentService,示例如下:


a.创建一个新的明确的intent给称作为RSSPullService的IntentService

/** * PhotoThumbnailFragment displays a GridView of picture thumbnails downloaded from Picasa */public class PhotoThumbnailFragment extends Fragment implements        LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {        private static final String STATE_IS_HIDDEN =            "com.example.android.threadsample.STATE_IS_HIDDEN";          ... ...          ... ...        /*         * Creates a new Intent to send to the download IntentService. The Intent contains the         * URL of the Picasa feature picture RSS feed         */        mServiceIntent =                new Intent(getActivity(), RSSPullService.class)                        .setData(Uri.parse(PICASA_RSS_URL));         ... ...         ... ... }

b.调用startService() 启动IntentService

/** * PhotoThumbnailFragment displays a GridView of picture thumbnails downloaded from Picasa */public class PhotoThumbnailFragment extends Fragment implements        LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {        private static final String STATE_IS_HIDDEN =            "com.example.android.threadsample.STATE_IS_HIDDEN";          ... ...          ... ...        // If there's no pre-existing state for this Fragment        if (bundle == null) {            // If the data wasn't previously loaded            if (!this.mIsLoaded) {                // Starts the IntentService to download the RSS feed data                getActivity().startService(mServiceIntent);            }         ... ...         ... ... }

注意:您可以在Activity 或者Fragment 中的任何地方发送这工作请求,例如, 如果您首先需要获得用户的输入,那您可以在button click 或者手势的 回调函数中发送该请求。一旦您调用了startService(), IntentService将在onHandleIntent()方法中处理这个请求,然后自动停止。

将处理后的结果报送回给请求源Activity 或者Fragment,将在下一篇“android 后台运行服务之报告工作状态篇”中讲述。