Skip to content

Instantly share code, notes, and snippets.

@jwoolston
Created August 18, 2013 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwoolston/6260008 to your computer and use it in GitHub Desktop.
Save jwoolston/6260008 to your computer and use it in GitHub Desktop.
Using shared preferences listener.
public class MyApp extends Application { //This is the Android Application object...
//if your app exists, so does it, and you are guarenteed only one
private String mPrefA;
private String mPrefB;
private mPrefsChanged = false; //Guarded by "this"
@Override
public void onCreate() {
//Fetch application preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
mPrefA = prefs.getString(getString(R.string.pref_key_A), "");
mPrefB = prefs.getString(getString(R.string.pref_key_B), "");
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
synchronized(this) {
if (key.equals(getString(R.string.pref_key_A))) {
mPrefA = sharedPreferences.getString(getString(R.string.pref_key_A), "");
mPrefsChanged = true;
} else if (key.equals(getString(R.string.pref_key_B))) {
mPrefB = sharedPreferences.getString(getString(R.string.pref_key_B), "");
mPrefsChanged = true;
}
}
}
public boolean havePrefsChanged() {
synchronized(this) {
mPrefsChanged = false;
return mPrefsChanged;
}
}
//Getters and setters for your preferences here, though I recomend a single data object which you update/provide atomicly,
//otherwise there will be a lot of flag checking and you arent guarenteed of its thread safety. Alternatively, you could register
//a thread safe LIST of listeners with this class and notify them of each change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment