20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

238 x CHAPTER 7 FILES, SAVING STATE,AND PREFERENCES<br />

Finding and Using the Shared Preferences<br />

Set by Preference Screens<br />

The Shared Preference values recorded for the options presented in a Preference Activity are stored<br />

within the application’s sandbox. This lets any application component, including Activities, Services,<br />

and Broadcast Receivers, access the values, as shown in the following snippet:<br />

Context context = get<strong>Application</strong>Context();<br />

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);<br />

// TODO Retrieve values using get methods.<br />

Introducing On Shared Preference Change Listeners<br />

The onSharedPreferenceChangeListener can be implemented to invoke a callback whenever a<br />

particular Shared Preference value is added, removed, or modified.<br />

This is particularly useful for Activities and Services that use the Shared Preference framework to<br />

set application preferences. Using this handler, your application components can listen for changes<br />

to user preferences and update their UIs or behavior, as required.<br />

Register your On Shared Preference Change Listeners using the Shared Preference you want<br />

to monitor:<br />

public class MyActivity extends Activity implements<br />

OnSharedPreferenceChangeListener {<br />

}<br />

@Override<br />

public void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

}<br />

// Register this OnSharedPreferenceChangeListener<br />

SharedPreferences prefs =<br />

PreferenceManager.getDefaultSharedPreferences(this);<br />

prefs.registerOnSharedPreferenceChangeListener(this);<br />

public void onSharedPreferenceChanged(SharedPreferences prefs,<br />

String key) {<br />

// TODO Check the shared preference and key parameters<br />

// and change UI or behavior as appropriate.<br />

}<br />

CREATING A STANDARD PREFERENCE ACTIVITY FOR THE<br />

EARTHQUAKE VIEWER<br />

Previously in this chapter you created a custom Activity to let users modify the application settings<br />

for the earthquake viewer. In this example you replace this custom Activity with the standard application<br />

settings framework described in the previous section.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!