I have a preference Activity, at first when I chance a preference the onPreferenceChange is triggered once as expected.
However, after some time (going to different activities and such) the onPreferenceChange is called twice.
I see in the debugger that the WeakHashMap for the mListeners is 1 in the beginning and then becomes greater than 1, but not sure why?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPrefs();
int preferencesResource = 0; // R.xml.preferences;
preferencesResource = getResources().getIdentifier("pref", "xml",
getPackageName());
addPreferencesFromResource(preferencesResource);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences arg0,
String arg1) {
// Why is this called once then sometimes twice!!
Log.i("PreferencesActivity", "OnPreferenceChanged()");
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
protected void onDestroy() {
super.onDestroy();
listener = null;
prefs.unregisterOnSharedPreferenceChangeListener(listener);
prefs = null;
}
public Preferences getPrefs() {
if (prefs == null) prefs = new Preferences(this);
return prefs;
}
You've placed unregisterOnSharedPreferenceChangeListener()
in onDestroy()
and it's not called on all activity restarts.
Look at the activity lifecycle diagram. Conclusion is that proper way to do this is to place registerOnSharedPreferenceChangeListener()
and unregisterOnSharedPreferenceChangeListener()
in onResume()
and onPause()
respectively.
This isn't for a LiveWallpaper by any chance is it? It sounds to me like you have two instances of the same class running(I.E. The LiveWallpaper itself as well as the preview because you're in settings). If it seems like they happen instantly right on top of each other and there is no delay than most likely you have the same listener running twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With