I have some preferences in my activity and I would like to achieve that, depending on these preferences, some services will be initiated or not.
I am trying to implement and onSharedPreferenceChanged
method, but it never gets called (even if I have assigned it to a field).
The code is the following:
public class MtprojectActivity extends Activity {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
callsCheckbox = prefs.getBoolean("callsLogChk", true);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (!started) {
startCallsService();
bindCallsService();
} else {
releaseCallsService();
stopCallsService();
}
}
};
prefs.registerOnSharedPreferenceChangeListen开发者_Python百科er(listener);
Thanks a lot in advance!
Are you sure it isn't being called or is it just a case of it not doing what you expect? I may be wrong but shouldn't the code look like this...
if (key.equals("callsLogChk")) {
if (!started) { // Check NOT started ???
startCallsService();
bindCallsService();
}
else { // The 'else' should compliment the check for !started ???
releaseCallsService();
stopCallsService();
}
}
Sorry, as I don't know your code I may be totally wrong but as you've posted it, it doesn't look quite right to me.
EDIT:
Also, are you making sure you call the SharedPreferences.Editor.commit()
method when you make the change to the preference?
精彩评论