开发者

Android preferences changed

开发者 https://www.devze.com 2023-03-24 04:48 出处:网络
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 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 onSharedPreferenceChangedmethod, 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消