一、关于Service组件
在Android四大组件中Service是唯一能够后台运行的服务,广播接收器是一个等待着的和观察者的角色,并不属于后台程序,此外,他的生命周期也非常短,在OnReceiver中不能超过有10秒的逻辑出现。
二、Service和IntentService
第1点:
IntentService的生命非常短暂,执行完onHandleIntent(Intent intent) 会自动结束;
第2点:
Service允许绑定服务,IntentService不允许绑定服务
第3点:
IntentService继承自Service,并且内部实现了Handler消息队列。注意,此队列无法实现并发。
第4点:
Service生命周期中,不可执行耗时任务(除了Binder方式),但IntentService可以,在IntentService中,onHandleIntent本身就是在异步环境中执行的方法。
三、关于Service的开机启动
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>