android怎么调用后台服务,Android中使用IntentService创建后台服务实例

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里注册。

android:icon="@drawable/icon"

android:label="@string/app_name">

...

android:name=".RSSPullService"

android:exported="false"/>

...

android:name属性指定了IntentService的类名。

注意:&ltservice&gt节点不能包含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实现。请参考此文:https://www.jb51.net/article/51548.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值