写在前头
保活Service我们需要做什么:
1.在应用被关闭后保活(最难)
2.在内用占用过大,系统自动释放内存时保活(优先杀死占用较高的Service)
3.重启手机后自动开启Service
4.手机息屏后不被释放内存
5.手动清理内存时保活
首先介绍一下Service的等级:
一、前台进程
二、可见进程
三、服务进程
四、后台进程
五、空进程 ---关闭应用后,没有清理缓存
所以为了提高优先级我们可以使用startForeground()方法将Service设置为前台进程。
一、在AndroidManifest中添加Service
android:process="istep.service" //放入新进程
>
android:process=":GuardService">
二、双进程保护
1.创建aidl实现跨进程通信(新建一个aidl)
interface ProcessConnection {
//删除不必要方法
}
2.创建主服务
public class StepService extends Service{
@Nullable
@Override
public IBinder
onBind(Intent intent) {
return new ProcessConnection.Stub() {};
}
@Override
public int
onStartCommand(Intent intent, int flags, int startId) {
startForeground(1,new Notification());
//绑定建立链接
bindService(new
Intent(this,GuardService.class),
mServiceConnection,
Context.BIND_IMPORTANT);
return START_STICKY;
}
private
ServiceConnection mServiceConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName
componentName, IBinder iBinder) {
//链接上
Log.d("test","StepService:建立链接");
}
@Override