在Android四大组件中Service是惟一可以后台运行的服务,广播接收器是一个等待着的和观察者的角色,并不属于后台程序,此外,他的生命周期也很是短,在OnReceiver中不能超过有10秒的逻辑出现。android
第1点:并发
IntentService的生命很是短暂,执行完onHandleIntent(Intent intent) 会自动结束;异步
第2点:ide
Service容许绑定服务,IntentService不容许绑定服务spa
第3点:.net
IntentService继承自Service,而且内部实现了Handler消息队列。注意,此队列没法实现并发。code
第4点:继承
Service生命周期中,不可执行耗时任务(除了Binder方式),但IntentService能够,在IntentService中,onHandleIntent自己就是在异步环境中执行的方法。生命周期
IntentService不适合常驻,所以,能够使用Service来实现。队列
package com.test.background; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BackBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent myIntent = new Intent(); myIntent.setAction("com.test.background.Service.network.Action"); //service服务的Action context.startService(myIntent); } } }
注册
<receiver android:name="com.test.background.BackBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver>
权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>