Default Shared Preferences give me wrong values in Service

前端 未结 2 386
鱼传尺愫
鱼传尺愫 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:17

    I found a solution thanks to this link Managing SharedPreferences in both PreferenceActivity and Service within same app and thanks to Andrew T. :

    The issue was the multi process mode. If you have a Service which is declared in the manifest with a android:process="" (which is my case) then it's necessary to set a multi process mode.

    Here is what i did :

    in PreferenceFragment :

    public static final String CONFIG_NAME = "pref";
    
    ...
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
    
    
        getPreferenceManager().setSharedPreferencesName(CONFIG_NAME);
        getPreferenceManager().setSharedPreferencesMode(Context.MODE_MULTI_PROCESS);
    
        addPreferencesFromResource(R.xml.config);
    
        ...
    }
    

    My Service :

    SharedPreferences settings = MyApplication.getInstance().getSharedPreferences(OptionsFragment.CONFIG_NAME, Context.MODE_MULTI_PROCESS);
    

    and I set the default values in MainActivity this way :

    PreferenceManager.setDefaultValues(getApplicationContext(), OptionsFragment.CONFIG_NAME, Context.MODE_MULTI_PROCESS, R.xml.config, false);
    

    And now it works fine. Hope it will help !

    Thank you again Andrew T.

提交回复
热议问题