I have written a foreground service which is working properly for all OS version lower than Oreo. From Oreo application process is getting killed after 5 minutes of closing
I faced the same issue in my OnePlus3 for my app. Then I noticed these lines in logcat, every time my app and Foreground service were killed:
10-12 18:30:40.644 1439 1519 I OHPD : [BgDetect]force stop com.mycompany.MyAndroidApp (uid 10905) level 0
10-12 18:30:40.645 1439 1519 I ActivityManager: Force stopping com.mycompany.MyAndroidApp appid=10905 user=0: from pid 1439
10-12 18:30:40.645 1439 1519 I ActivityManager: Killing 23139:com.mycompany.MyAndroidApp/u0a905 (adj 200): stop com.mycompany.MyAndroidApp
10-12 18:30:40.647 1439 1519 W ActivityManager: Scheduling restart of crashed service com.mycompany.MyAndroidApp/md55852635cfc9dced970aa39ae09e74ead.MyForegroundService in 1000ms
10-12 18:30:40.651 1439 1519 I ActivityManager: Force finishing activity ActivityRecord{a5c8d39 u0 com.mycompany.MyAndroidApp/md55852635cfc9dced970aa39ae09e74ead.MainActivity t3108}
10-12 18:30:40.655 1439 1519 I ActivityManager: Force stopping service ServiceRecord{6052f94 u0 com.mycompany.MyAndroidApp/md55852635cfc9dced970aa39ae09e74ead.MyForegroundService}
10-12 18:30:40.660 1439 1519 I OHPD : [BgDetect]chkExcessCpu level: 1 doKills: true critical false uptime: 300328
10-12 18:30:40.710 1439 8213 I WindowManager: WIN DEATH: Window{c381342 u0 com.mycompany.MyAndroidApp/md55852635cfc9dced970aa39ae09e74ead.MainActivity}
Then searching the internet for the keywords 'OHPD : [BgDetect]chkExcessCpu level: 1 doKills: true' took me to this SO answer:
Prevent background service from being killed due to "detect excessive cpu on forked process"
As suggested in that answer and the GitHub issue, Locking / Pinning my app prevented Oxygen OS from killing my app (MainActivity and Forground Service).