开发者

onSharedPreferenceChanged called multiple times.... why?

开发者 https://www.devze.com 2023-02-24 07:49 出处:网络
I have a preference Activity, at first when I chance a preference the onPreferenceChange is triggered once as expected.

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开发者_Python百科 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消