Android Listening for SharedPreferences changes


Example

SharedPreferences sharedPreferences = ...;
sharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);


private final SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        //TODO
    }
}

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.