8.0系统杀服务杀的很频繁,有的时候APP进入后台,比如在打电话的时候,就很容易被系统杀掉,为了保活,我们使用了两个不在同一个进程的Service互保的方式,即:android:process=":f"的方式
<service
android:name=".guard.RemoteService"
android:enabled="true"
android:exported="true"
android:process=":RemoteProcess" />
<service
android:name=".guard.LocalService"
android:enabled="true"
android:exported="true" />
但是通过startService方法启动保活服务的时候会有IllegalStateException异常
java.lang.IllegalStateException: Not allowed to start service Intent {
解决方法:8.0以后启动前台服务: startForegroundService(intent);
@Override
public void onServiceDisconnected(ComponentName name) {
LogUtil.e(TAG, "onServiceDisconnected: 链接断开,重新启动 RemoteService");
Intent intent = new Intent(LocalService.this,RemoteService.class);
if (Build.VERSION.SDK_INT >=26){
startForegroundService(intent);
}else {
startService(intent);
}
bindService(new Intent(LocalService.this,RemoteService.class),connection, Context.BIND_IMPORTANT);
}