androidpreferenceactivity

OnSharedPreferenceChangeListener fires when the user enters in the preference activity the first time


I've a PreferenceActivity and a Service in my application among other components.

When a preference is changed, I want my service to do some work depending on the preference changes, so I configured my service as a OnSharedPreferenceChangeListener.

My problem is when the user enters in the preference activity the first time. The OnSharedPreferenceChange event is fired once per preference in the "preferences.xml", although no preference has been changed.

How could I avoid this behaviour? I don't want the OnSharedPreferenceChange event is fired the first time the user enters in the "preferences activity".

Thanks


Solution

  • Just use a flag in sharedpreferences, just like that

     if( prefs.getBoolean( "preferenceFirstTime", true ) ) {
          SharedPreferences.Editor editor = prefs.edit();
          editor.putBoolean("preferenceFirstTime", false);
          editor.commit();
     } else {
          //this is not the first time 
     }