I am wondering what strategies others use to avoid data loss when saving files on Android. I have a couple of game apps that and essentially, they potentially save the game state/savegame whenever the user pauses (onPause).
This works in 99.99% of the cases, but every once in a while I receive an example of a savegame where the saving process has gone wrong. Usually, this is an ill-formed XML file, typically truncated at some arbitrary point. Based on the bug reports I receive, I believe that the problem mostly occurs when the user is interrupted during gameplay by a phone call or something like that and the Android OS then kills the app before it can finish saving. The code for saving the files is pretty simple, so I have difficulty seeing what else might cause this issue.
This is a serious problem, because it will usually result in the player's save progress being ruined.
I was thinking of writing to an empty file first, and then copying to the "real" file only after, but I suspect that would simply increase the problem as it will overall take more time and still risks getting interrupted.
Anyone who has a secure way of doing this that Android is relatively guaranteed not to mess up?
So summarized, the options suggested so far (as I understand them):
- Use a service for the saving process, on the assumption that this will be less likely to be killed by the OS.
- Save in temp file; copy over when save is verified.
- Incremental saving of the game state (I actually already use this for player log information).
- Combination of 2 & 3.
- Move the saving to another thread, as the problem may be with ANR kills [DC's comments below].
I do not think SharedPreferences will work for this kind of structured data, At the moment, neither of these methds seem like an ideal solution, so I am still open to suggestions.
I've not yet managed to test all of these approaches, so rather than waste the bounty, I have assigned it to the answer that I feel would be most likely to solve the issue. I plan to check through the various options still, though, prior to accepting an answer. Thanks for all of the good suggestions.