I have a service which is required to run for long periods of time in the background. A foreground service is not suitable due to the notification. It needs to run quietly in the background doing it's polling. It does this already and behaves as it should. This is not my problem, this is just some background.
When the service is killed by the user and onDestroy() is called, the data is saved to the db - No problem there. Also when the phone is turned off I have a broadcast receiever which listens for screenoff/on. Again no problem saving there.
The Problem is when the OS kills the service due to low memory. The service is killed and I don't believe onDestroy() is called. If it is, my data is not stored. So if the service is killed and has been running for a while, all the information it has gathered is lost.
So after all that, my question is: How should I gracefully clean up my resources and save my data? Is there a way I can run some code to save my data before the system kills my service? I have considered making my service save to the database at intervals of a few minutes to reduce the amount of data loss. I am not sure how good this is performance wise. The queries would likely only be inserting up to 30 rows in a period of say 5 minutes. Likely less.
I am a relatively new to Android development and have tried my best to look up this problem before coming here to ask a question. Apologies if I have overlooked something.
Thanks!