Android 8.0 (o) 限制后台service服务的启动问题

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);
        }
发布了316 篇原创文章 · 获赞 63 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/ytfunnysite/article/details/102502119