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());