简体   繁体   English

Android-从活动到广播接收器获取首选项

[英]Android - Get preference from activity to broadcast receiver

I'm developing an Android app but I have a problem. 我正在开发一个Android应用程序,但是有问题。 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. 当我尝试从Activity中获取保存的首选项并在BroadcastReceiver使用它时,它告诉我我要查找的字符串不存在。

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 : 这就是我尝试在BroadcastReceiver获得首选项的方法:

String pref = PreferenceManager.getDefaultSharedPreferences(context)
  .getString("MEM1", "Does not exist");

Where MEM1 is the string I saved before. MEM1是我之前保存的字符串。

My problem is that when I read pref , I'm getting the default value of Does not exist , instead of my preference value ( MEM1 ). 我的问题是,当我阅读pref ,得到的是默认值Does not exist ,而不是我的首选值( MEM1 )。 Can someone point me to where I'm going wrong? 有人可以指出我要去哪里了吗?

Activity.getPreferences(mode);

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). 返回特定于该活动的SharedPreferences实例(例如,支持该XML文件的名称将与该活动相同),而默认共享首选项特定于该应用程序(XML名称将基于您的包名称) )。

Either provide a custom file name every time you retrieve SharedPreferences, or stick to the default. 每次检索SharedPreferences时都提供一个自定义文件名,或者坚持默认设置。

You Should Use.. 您应该使用..

private void SavePreferences(String key, String value){

        SharedPreferences sharedPreferences = getPreferences("my_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
       }

And Then 接着

String pref = getSharedPreferences("my_prefs", MODE_PRIVATE).getString("MEM1", "Does not exist");

Also Make Sure Your Key Is Correct. 还要确保您的密钥是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM