Problems using SharedPreferences on a Service (getPreferences doesn't exist on a service)

后端 未结 5 1459
無奈伤痛
無奈伤痛 2020-12-13 14:03

I have some shared preferences (latitude, longitude) that I want to access from a service, that is not subclassed from Activity.

In particular, when I try to access

5条回答
  •  余生分开走
    2020-12-13 14:29

    Actually, most of you might be running into the problem, that on devices with API >=11, the shared preferences are not set for multi process use by default anymore.

    Solution:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        prefs = getSharedPreferences(PREFS, 0 | Context.MODE_MULTI_PROCESS);
    } else {
        prefs = getSharedPreferences(PREFS, 0);
    }
    

提交回复
热议问题