Finding and Using the Shared Preferences Set by Preference Screens

The Shared Preference values recorded for the options presented in a Preference Activity are stored within the application’s sandbox. This lets any application component, including Activities, Services, and Broadcast Receivers, access the values, as shown in the following snippet:

Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// TODO Retrieve values using get<type> methods.

Introducing On Shared Preference Change Listeners

The onSharedPreferenceChangeListener can be implemented to invoke a callback whenever a particular Shared Preference value is added, removed, or modified.

This is particularly useful for Activities and Services that use the Shared Preference framework to set application preferences. Using this handler, your application components can listen for changes to user preferences and update their UIs or behavior, as required.

Register your On Shared Preference Change Listeners using the Shared Preference you want to monitor:

public class MyActivity extends Activity implements
 OnSharedPreferenceChangeListener {
 public void onCreate(Bundle savedInstanceState) {
 // Register this OnSharedPreferenceChangeListener
 SharedPreferences prefs = 
 public void onSharedPreferenceChanged(SharedPreferences prefs, 
 String key) {
 // TODO Check the shared preference and key parameters 
 // and change UI or behavior as appropriate.

Leave a Comment