Caused by java.lang.IllegalStateException Not allowed to start service Intent { cmp=com.x.x.x/.x.x.xService }: app is in background uid UidRecord(一)

Caused by java.lang.IllegalStateException
Not allowed to start service Intent { cmp=com.x.x.x/.x.x.xService }: app is in background uid UidRecord{7d9f297 u0a184 SVC bg:+15m25s900ms idle change:uncached procs:3 seq(0,0,0)}
 
Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,则该函数将引发一个 IllegalStateException。 新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行, 系统也允许其调用 Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。
 

解决方法:
1. 修改启动方式

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

2. 并且在service里再调用startForeground方法,不然就会出现ANR

context.startForeground(SERVICE_ID, builder.getNotification());

 https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexception-not-allowed-to-start-service-inten

app is in background uid UidRecord问题原因分析

https://www.cnblogs.com/mingfeng002/p/10725364.html

原文地址:https://www.cnblogs.com/mingfeng002/p/9647720.html