Android SharedPreferences Listening for SharedPreferences changes


SharedPreferences sharedPreferences = ...;

private final SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

Please note:

  • The listener will fire only if value was added or changed, setting the same value won't call it;
  • The listener needs to be saved in a member variable and NOT with an anonymous class, because registerOnSharedPreferenceChangeListener stores it with a weak reference, so it would be garbage collected;
  • Instead of using a member variable, it can also be directly implemented by the class and then call registerOnSharedPreferenceChangeListener(this);
  • Remember to unregister the listener when it is no more required using unregisterOnSharedPreferenceChangeListener.