Android preference change listener implementation

Android preference change listener implementation

In Android applications, there are scenarios we need to listen for changes to preferences. For example, a main activity would like to refresh itself based on a change in preference. Android provides the OnSharedPreferenceChangeListener which would help in achieving this.

The following example demonstrates the preference change listener.

Android preference change listener example

Implement a preference change listener in the main activity.

private class PreferenceChangeListenerimplements OnSharedPreferenceChangeListener {@Overridepublic void onSharedPreferenceChanged(SharedPreferences prefs, String key) {if ( key.equals("test_preference_key") ) {Log.v("PreferenceChange", "**** KEY test_preference_key modified ****");}}}

Preferences XML looks as below for the above listener. We have a “test_preference_key” whose changes this activity is interested in listening.

<?xml version="1.0" encoding="utf-8"?><PreferenceScreen ><PreferenceCategory android_key="test_category_key" android_title="@string/test_category_string"><EditTextPreference android_title="@string/test_preference_string"android:key="test_preference_key"android:summary="@string/test_preference_summary_string"></EditTextPreference></PreferenceCategory></PreferenceScreen>

Create an object of preference change listener and register for change notifications in onCreate method of the activity.

@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mPrefs = PreferenceManager.getDefaultSharedPreferences(this);mPreferenceListener = new PreferenceChangeListener();mPrefs.registerOnSharedPreferenceChangeListener(mPreferenceListener);}

Un-register the preference change listener in the activity onDestroy method.

@Overridepublic void onDestroy() {super.onDestroy();mPrefs.unregisterOnSharedPreferenceChangeListener(mPreferenceListener);}

The complete example can be downloaded from here.
PreferenceChange