How to keep Android ForegroundService running indefinitely in newer versions of Android?

Viewed 142

I'm graduating from a computer science college and as a diploma project I want to build an Android app that monitors user's battery and then can use root to disable the charging of the phone. First step is to monitor the battery and the usage pattern of the user and offer them some stats.

To monitor the battery I use a foreground service that queries the battery status from time to time via a broadcast receiver for the ACTION_BATTERY_CHANGED event. But I have problems keeping my foreground service alive. It keeps working for 10-15 minutes but it eventually gets killed by the system (I thought maybe it was because the events were coming quite rarely). I also tried using coroutines to delay the querying and doing it manually every 1 minute and then even more often like 30 seconds but my service still gets killed eventually and won't be started again in the near future even though is started with START_STICKY. I also tried setting alarms via the AlarmManager to restart my service from time to time but I still can't get a consistent pattern of battery data in order to be able to analyse and build an estimation algorithm for the core of my project.

I am running Android 9 on a OnePlus 5T as my testing device and have a really hard time with keeping the foreground service alive. But I observed that there are apps like Mi Fit, Mi Band Tools or even this battery app that manage to somehow restart their foreground services when they get stopped. I can see my screen lighting up and showing me that one of those app got stopped but when I open my notifications I can see that the foreground notification is still there for that app, so probably it got restarted right away (but when the same thing happens for my app, my foreground notification is not there any more).

I also tried overriding OnDestroy inside my service and restart it from there but it seems like the OnDestroy method doesn't get called, the system just kills the process probably when needing more memory. I also can't use BroadcastReceivers registered in the Manifest because they don't work any more from Android 8+ (which most tutorials recommend to do).

I read everything I could get my hands on on this topic and nothing really worked.. The best approach was setting alarms via AlarmManager but even that stopped working after a few hours but somehow the other apps keep on working and I'm interested to find out how I should do this in newer Android versions (Android 8 and over preferably).

Thank you!

1 Answers

By using Workmanager start a PeriodicWork and check if foreground service is running,if not start the service inside doWork() method

Related