This is especially useful for saving (and loading) your game's state. It uses SD card by default, but it degrades gracefully to internal memory when the SD card is unavailable. "Why should I save game state to SD card?", you might ask. Well, large part of Android users are using custom ROMs on their devices. They upgrade it often and they often have to wipe the internal memory. Nobody wants to lose progress in any game, so storing it SD card seems better to me. Besides, if you switch phones, it's easy to copy or backup your savegames. Digression aside, let's dive into the code!
1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829
- getExternalStorageDirectory() - returns the root SD card directory (it's a method of
android.os.Environment). Use this, instead of hardcoding the
/sdcard(or any other) path!
- context.openFileOutput(fileName, 0) - opens a file associated with this Context's application package (in device's internal memory). More info in the docs.
1 2 3 4 5 6 7 8 91011121314151617181920212223
1 2 3 4 5 6 7 8 910111213141516