如何在 Android 的接收器/服务中获取 CheckBoxPreference 值?
我在 PreferenceActivity
中使用 CheckBoxPreference
来设置值。稍后,我想从接收者和/或服务中检查该值。 findPreference()
方法在该上下文中不可用。我知道,这个首选项值无论如何都存储在 SharedPreferences 中,但关键是什么?我怎样才能获得复选框的值?
I use CheckBoxPreference
in my PreferenceActivity
to set a value. Later on, I want to check that value from Receiver and/or Service. findPreference()
method is not available from that context. I know, that this preference value is stored in SharedPreferences
anyway, but what is the key? How could I get the value of the checkbox?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无论您在首选项 XML 中为
android:key
设置什么值。调用
PreferenceManager.getDefaultSharedPreferences()
获取SharedPreferences
,然后使用您在android:key< 中使用的键调用
getBoolean()
/代码>。Whatever value you have for
android:key
in your preference XML.Call
PreferenceManager.getDefaultSharedPreferences()
to get theSharedPreferences
, then callgetBoolean()
with the key you used inandroid:key
.在您的首选项 XML 中,您将具有如下内容:
您的 strings.xml 将具有如下内容:
您的 Activity 的 onCreate() 将具有如下内容:
如果您想在有人更改首选项时执行某些操作,请添加 onActivityResult()到您的活动并使用 startActivityForResult() 启动首选项活动。当使用您想要指示首选项更改的任何结果代码调用 onActivityResult() 时,您可以执行另一个 getDefaultSharedPreferences()。
共享首选项框架会自动保留数据...您不必自己主动处理它,但如果您愿意,可以在首选项活动中使用 OnPreferenceChangeListener
In your preferences XML you'll have something like this:
Your strings.xml would have something like this:
Your Activity's onCreate() would have something like this:
If you want to do something when someone changes the preferences, add an onActivityResult() to your activity and start the preferences activity with startActivityForResult(). When onActivityResult() is invoked with whatever result code you want to indicate a change in preferences, you can do another getDefaultSharedPreferences().
The shared preferences framework automatically persists the data... you don't have to actively deal with it yourself, though you can if you wish with an OnPreferenceChangeListener in the preferences activity
我要在 CommonsWare 的答案中添加的唯一一件事是,既然您提到了一项服务,您可以将该服务需要了解的任何首选项放入其 Intent extras 中。例如:
The only thing I would add to CommonsWare's answer is, since you mentioned a service, you can put whatever preferences the service needs to know about in its Intent extras. For example:
尝试在您的服务中编写此内容
,并在此处指定您在 xml 中使用的密钥
希望这会有所帮助。
try to write this in your service
and here specify the key that you have used in xml
hope this help .