Default Shared Preferences give me wrong values in Service

前端 未结 2 415
鱼传尺愫
鱼传尺愫 2021-01-19 14:33

I have a PreferenceFragment where I have defined a CheckBoxPreference in XML. I need to check this value in a Service, but it always gives me the old value. I noticed the va

2条回答
  •  半阙折子戏
    2021-01-19 15:07

    I had the same issue for the last days...

    I have a preference.xml with my layout and keys and inflate it into a PreferenceFragment while Listening on changes and thereby informing a Service of my Application of any change. The crucial part is to set the mode of the SharedPreference access right:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceManager().setSharedPreferencesMode(Context.MODE_MULTI_PROCESS);
    }
    

    The Context.MODE_MULTI_PROCESS flag makes commits() apply to all accessing processes so even my Service would get direct access to the just changed values.

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
    {
        if(SettingsManager.setupIsValid(getActivity())){
            Intent startServiceIntent = new Intent(getActivity(), IntentService.class);
            startServiceIntent.setAction("PREFERENCES_CHANGED");
            getActivity().startService(startServiceIntent);
        } else {
            Toast.makeText(getActivity(), getString(R.string.settings_incomplete), Toast.LENGTH_SHORT).show();
        }
    }
    

    This will first do check magic and whenever the settings are valid inform the service of the change.

    This allows the usage of multiple processes and always current preference values across all processes.

    P.S.: direct access then looks like this

    SharedPreferences prefs = context.getSharedPreferences(context.getPackageName() + "_preferences", Context.MODE_MULTI_PROCESS);
    

提交回复
热议问题