美文网首页Android 知识
Android 8.0 启动Service适配(Not allo

Android 8.0 启动Service适配(Not allo

作者: 雨田Android开发 | 来源:发表于2021-04-19 10:29 被阅读0次

问题现象:
App出现异常: java.lang.IllegalStateException: Not allowed to start service Intent xxxx app is in background uid UidRecord

App直接崩溃。

问题原因:
App targetSdkVersion>= 26的情况下,用户允许App开机自启动,App被杀死或者系统重启后,系统直接将App后台启动起来,App在后台启动的过程中有使用startService()方法。

Google在Android 8.0之后对于处于后台的App启动Service进行了严格的限制,不再允许后台App启动后台Service,如果使用会直接抛出异常。
解决方法:
使用startForegroundService,此方法会在状态栏显示通知

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            Intent intent = new Intent(SplashActivity.this, MyService.class);
                            intent.putExtra("init", true);
                            startForegroundService(intent);
                        }else{
                            Intent intent = new Intent(SplashActivity.this, MyService.class);
                            intent.putExtra("init", true);
                            startService(intent);
                        }

在service的oncreate中加入如下代码

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = null;
            channel = new NotificationChannel(CHANNEL_ID_STRING, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            startForeground(1, notification);
        }

去除状态栏方法
stopForeground()

相关文章

网友评论

    本文标题:Android 8.0 启动Service适配(Not allo

    本文链接:https://www.haomeiwen.com/subject/hvqilltx.html