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
use startForeground(id, notification)
method inside your service.
User should know that something, that cant be killed by system, is working in background, so android system should inform user with a notification, so user knows exactly what is killing his battery.
By the way you can use WakeLock.
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PARTIAL_WAKE_LOCK,
TAG_FOR_DEBUG);
wakeLock.acquire()
But read about WakeLock before using it. And don't forget to disable it when your work is finished.
You can check current enabled wake locks using adb shell dumpsys power
command in the Terminal