get SharedPreferences from a service

非 Y 不嫁゛ 提交于 2019-12-01 17:52:42

问题


I am trying to access shared preferences from a service. I have used the the following to save the value of text to a string...

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Ignore1_value", Example.getText().toString());
editor.commit();

But, how would i get the value in a service? Everything i have tried returns as nothing. Any help would be perfect and much appreciated?

I looked through some other questions as well with no solution. I have came up with this, but like i said it returns it as no text.

Context ctx = getApplicationContext();
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    String example1string = sharedPreferences.getString("Ignore1_value","");
    Log.i("**GetSettings", example1string);

回答1:


I'm always using PreferenceManager.getDefaultSharedPreferences(context). This is the same for all Contexts in your application.

A Service is a Context itself, so this would be sufficient:

PreferenceManager.getDefaultSharedPreferences(this);


来源:https://stackoverflow.com/questions/11377564/get-sharedpreferences-from-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!