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

后端 未结 5 1446
無奈伤痛
無奈伤痛 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:32

    If you have declared SharedPreferences as:

    private static final String PREFS_NAME = "UserData"; 
    private static final String PREFS_VALUE1 = "value1"; 
    

    then use the below code to fetch values:

    SharedPreferences preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    value1 = preferences.getString(PREFS_VALUE1, "0");
    

    In same way you can even save values to SharedPreferences.

提交回复
热议问题