Game Development Reference
In-Depth Information
Shared Preferences
Android provides a simple API for storing key-value pairs for your application, called
SharedPreferences. The SharedPreferences API is not unlike the standard Java Properties
API. An activity can have a default SharedPreferences instance or it can use as many different
SharedPreferences instance as required. Here are the typical ways to get an instance of
SharedPreferences from an activity:
SharedPreferences prefs = PreferenceManager. getDefaultSharedPreferences ( this );
or:
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
The first method gives a common SharedPreferences that will be shared for that context
( Activity , in our case). The second method does the same, but it lets you choose the privacy
of the shared preferences. The options are Context.MODE_PRIVATE , which is the default,
Context . MODE_WORLD_READABLE , and Context.MODE_WORLD_WRITEABLE . Using anything other than
Context.MODE_PRIVATE is more advanced, and it isn't necessary for something like saving game
settings.
To use the shared preferences, you first need to get the editor. This is done via
Editor editor = prefs.edit()
Now we can insert some values:
editor.putString("key1", "banana");
editor.putInt("key2", 5);
And finally, when we want to save, we just add
editor.commit();
Ready to read back? It's exactly as one would expect:
String value1 = prefs.getString("key1", null);
int value2 = prefs.getInt("key2", 0);
In our example, value1 would be "banana" and value2 would be 5 . The second parameter
to the “get� calls of SharedPreferences are default values. These will be used if the key isn't
found in the preferences. For example, if "key1" was never set, then value1 will be null after
the getString call. SharedPreferences are so simple that we don't really need any test code to
demonstrate. Just remember always to commit those edits!
Audio Programming
Android offers a couple of easy-to-use APIs for playing back sound effects and music files—just
perfect for our game programming needs. Let's have a look at those APIs.
 
Search WWH ::




Custom Search