title: Avoiding data loss due to interruption when saving files on android?
body: <p>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).</p>
  
  <p>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.</p>
  
  <p>This is a serious problem, because it will usually result in the player's save progress being ruined.</p>
  
  <p>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.</p>
  
  <p>Anyone who has a secure way of doing this that Android is relatively guaranteed not to mess up?</p>
  
  <hr>
  
  <p>So summarized, the options suggested so far (as I understand them):</p>
  
  <ol>
  <li>Use a service for the saving process, on the assumption that this will be less likely to be killed by the OS.</li>
  <li>Save in temp file; copy over when save is verified.</li>
  <li>Incremental saving of the game state (I actually already use this for player log information).</li>
  <li>Combination of 2 &amp; 3.</li>
  <li>Move the saving to another thread, as the problem may be with ANR kills [DC's comments below].</li>
  </ol>
  
  <p>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.</p>
  
  <hr>
  
  <p>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.</p>