Android - 从活动到广播接收器获取偏好
我正在开发 Android 应用程序,但遇到问题。当我尝试从 Activity 中获取已保存的首选项并在 BroadcastReceiver
中使用它时,它告诉我我正在查找的字符串不存在。
这就是我在 Activity 中保存首选项的方法:
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
这就是我尝试在 BroadcastReceiver
中获取首选项的方法:
String pref = PreferenceManager.getDefaultSharedPreferences(context)
.getString("MEM1", "Does not exist");
其中 MEM1
是我之前保存的字符串。
我的问题是,当我读取 pref
时,我得到的默认值是 不存在
,而不是我的首选项值 (MEM1
) 。有人能指出我哪里出错了吗?
I'm developing an Android app but I have a problem. When I try to get a saved preference from my Activity and use it in a BroadcastReceiver
, it tells me that string I'm looking for doesn't exist.
This is how I save the preference in the Activity:
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
And this is how I try to get the preference in BroadcastReceiver
:
String pref = PreferenceManager.getDefaultSharedPreferences(context)
.getString("MEM1", "Does not exist");
Where MEM1
is the string I saved before.
My problem is that when I read pref
, I'm getting the default value of Does not exist
, instead of my preference value (MEM1
). Can someone point me to where I'm going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用..
然后
还要确保您的密钥是正确的。
You Should Use..
And Then
Also Make Sure Your Key Is Correct.
返回特定于该 Activity 的 SharedPreferences 实例(例如,支持它的 XML 文件将被命名为与该 Activity 相同的名称),而默认共享首选项特定于应用程序(XML 名称将基于您的包名称)。
每次检索 SharedPreferences 时都提供自定义文件名,或者坚持使用默认值。
returns an instance of SharedPreferences that is specific to that Activity (as in, the XML file backing it will be named the same as the activity), while default shared preferences is specific to the application (the XML name will be based on your package name).
Either provide a custom file name every time you retrieve SharedPreferences, or stick to the default.