8

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!

4

1 回答 1

3

如果您的服务被 os 杀死,则您的任何代码都不会在此事件上执行,因此您需要在数据更改后保存数据。

事实上,如果在 onStartCommand() 中返回 Service.START_STICKY_COMPATIBILITY,后台服务将重新启动,这是默认选择,您无需担心。只需在您的服务中进行快速初始化并尽快保存您的结果。

于 2013-07-25T11:21:36.713 回答