IntentService 类就提供了直接的后台线程操作。不过它也是有限制的:
- 不能直接与用户操作交互,如果要将 结果显示 在UI,你必须把他们送到 Activity
- 工作请求是有顺序的,如果一个工作正在进行,此时你发起一个请求,那么请求会被搁置,直到第一个操作结束
- 在 intentService 中的操作是不可以打断的
不过,大部分情况下,简单的后台工作都是可以用 intentService
完成
IntentService
创建一个intentService
intentService一样是你的app的一个组件,定一个继承与IntentService的类。在其中重写必要方法
public class RSSPullService extends IntentService {
@Override
protected void onHandleIntent(Intent workIntent) {
// 从传入的intent中获取数据
String dataString = workIntent.getDataString();
...
// 通过data,开始工作
...
}
}
**同时**intentService需要清单文件中,提供一个 <service>
元素
<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/>
service
的名字就是 IntentService的名字
创建一个Work Request给一个IntentService
// 创建一个 intent
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
// 设置数据
mServiceIntent.setData(Uri.parse(dataUrl));
// 开始一个service任务
getActivity().startService(mServiceIntent);
要注意的有:
在任何地方都可以开始一个 service
一旦你调用 startService
, 那么IntentService就会在 onHandleIntent
方法中开始工作,完成后自我停止,然后报告工作的结果。
反馈 IntentService 报告工作状态
用 localBroadcastManager
来向 对象的UI 来反馈一个结果
要获取一个 intent 对象,要使用一个 broadcastReceiver
的子类,实现 BroadcastReceiver.onReceive()
方法来接收一个传入的intent
比如:
private class ResponseReceiver extends BroadcastReceiver
{
// 预防实例化
private DownloadStateReceiver() {
}
// 调用 BroadcastReceiver 来获取 Intent
public void onReceive(Context context, Intent intent) {
...
/*
* 在这里处理 传入的 intent
*/
...
}
}
一旦你定义好 BroadcastReceiver,你就可以定义 filters(筛选器),创建一个 IntentFliters
public class DisplayActivity extends FragmentActivity {
...
public void onCreate(Bundle stateBundle) {
...
super.onCreate(stateBundle);
...
// The filter's action is BROADCAST_ACTION
IntentFilter mStatusIntentFilter = new IntentFilter(
Constants.BROADCAST_ACTION);
// Adds a data filter for the HTTP scheme
mStatusIntentFilter.addDataScheme("http");
...
在 注册 BroadcastReceiver
和 IntentFilter
,获取 localBroadcastReceiver
调用 registerReceiver()
方法
// Instantiates a new DownloadStateReceiver
DownloadStateReceiver mDownloadStateReceiver =
new DownloadStateReceiver();
// Registers the DownloadStateReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(
mDownloadStateReceiver,
mStatusIntentFilter);
...
一个 BroadcastReceiver
可以处理多个类型的 Intent。