Created
August 18, 2013 05:18
-
-
Save jwoolston/6260008 to your computer and use it in GitHub Desktop.
Using shared preferences listener.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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