How To Update Main Activity To Know That Prefs Are Changed?
Solution 1:
You could either re-read all the preferences in Activity.onResume()
, or as long as your main activity launches the preferences activity (e.g. from a menu), you could launch with startActivityForResult(Intent, int)
and re-read all the preferences in onActivityResult(int, int, Intent)
.
I have also found it sufficient to re-check each relevant preference before starting the appropriate behavior (i.e. before issuing the Notification
for your example).
Solution 2:
You need to implement the onSharedPreferenceChangeListener interface. Then register to receive change updates in your onCreate/onStart:
myPreferences.registerOnSharedPreferenceChangeListener();
In your listener you do something like this:
@OverridepublicvoidonSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("MyKey")) {
// Do something.
} elseif (key.equals("MyOtherKey")) {
// Do something else.
}
}
Remember to remove the listener in onStop/onDestroy.
Solution 3:
You can create a static boolean that is changed whenever a preference is changed, or when your preference activity is started. The purpose of this boolean is to let your main activity know the preferences are dirty and need to be reloaded. They should be reloaded onResume
if the mDirty
flag is true.
Another option is to just reload all the preferences onResume
, regardless. This may not be as efficient, but if you don't have loads of preferences, it's fine.
The most efficient way would be to set onPreferenceChanged listeners for all your prefs in your prefs activity, the prefs then notify the activity only when they actually change. This solves the case when your user enters your prefs activity, but doesn't actually change anything.
Post a Comment for "How To Update Main Activity To Know That Prefs Are Changed?"