Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I store my game level state?

Tags:

java

android

I have a game where I draw and move bitmaps over a SurfaceView. The user can interact (drag and drop) these bitmaps. When the player hits the home button then goes back into the game, I want to be able to pause the game, then restore it to where it was before he left it. What is the best way to store my custom objects?

  1. Should I implement onSaveInstanceState(Bundle) and have all of the classes whose objects I want to save implement the Parcelable interface? This would be quite a bit of work, and I'm still not sure how I would save things like bitmaps. I suppose I wouldn't and I would just reload those from disk.

    I am also confused about what kind of storage a bundle offers: disk storage that never goes away unless you clear it yourself, or memory storage that goes away if the OS decides to remove your program from memory while it's in the background. According to the comments in this question, it is disk storage. The documentation implies that it is memory storage, saying Note that it is important to save persistent data in onPause(), however I don't find it very clear. This page also implies that it is not persistent: it only lasts as long as the application remains in memory. So which one is it?

  2. The last link above suggests using onRetainNonConfigurationInstance() to keep objects in memory while the application is in the background. This would imply that if the program is taken out of memory by the OS while in the background, everything would be lost. This seems to be what most (all I tested on) games do: if you hit home while playing then go back in, the level resumes. If you hit home, open a lot of stuff (sufficient to make Android remove the game from memory), then go back in, nothing is resumed, the game starts from the main menu. Does that mean this is what they use, and if so, is that a good practice?

Note that the question about a Bundle's persistency is just a secondary curiosity. I don't really care if the state of this game is not permanently saved and can be lost after the game being in the background for a while (as described in 2 above). I'm interested in the best practice for this case.

like image 750
IVlad Avatar asked Mar 17 '12 21:03

IVlad


1 Answers

The basic idea is, IMO, identify the smallest collection of values that will enable you to recreate the state of your game. Save those in shared preferences.

like image 193
Sparky Avatar answered Sep 28 '22 05:09

Sparky