I have a game app that save game status in the onPause() function of the game board activity.
That seems very wasteful, because the user might be briefly switching to another app and return to play later. But if they never return, my app could be garbage collected and the status gets lost, so I save it just in case.
I think status gets saved many times for every time it gets read. Is there a better way to lazily save the status when I know they are leaving the app?
Does anybody know of a guaranteed callback that I could use? e.g. if I move the save status code to onDestroy(), it might never get called.
Is there a way to leverage onSaveInstanceState() to help?
Thanks
onPause() gets called when the user switches orientation and when the user navigates away. Both of these actions have the potential for data loss, so saving in onPause() is a good idea, no matter what you’re making (be it a game or an app).
So no, onPause() is the safest way to ensure data persistence.
EDIT
To answer your second question, onSavedInstanceState() is not clear cut
So for a game, I would aggressively save the player’s data, and would do so in onPause(). Everything else either has potential to fail or isn’t directly related to the Activity lifecycle.