Reading Preferences


  By default, all your app's preferences are saved to a file that's accessible from anywhere within your application by calling the static method PreferenceManager.getDefaultSharedPreferences(). This returns theSharedPreferences object containing all the key-value pairs that are associated with the Preference objects used in your PreferenceActivity.

For example, here's how you can read one of the preference values from any other activity in your application:

 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "");

Listening for preference changes

  There are several reasons you might want to be notified as soon as the user changes one of the preferences. In order to receive a callback when a change happens to any one of the preferences, implement theSharedPreference.OnSharedPreferenceChangeListener interface and register the listener for theSharedPreferences object by calling registerOnSharedPreferenceChangeListener().

The interface has only one callback method, onSharedPreferenceChanged(), and you might find it easiest to implement the interface as a part of your activity. For example:

 public class SettingsActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
... public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}

  In this example, the method checks whether the changed setting is for a known preference key. It callsfindPreference() to get the Preference object that was changed so it can modify the item's summary to be a description of the user's selection. That is, when the setting is a ListPreference or other multiple choice setting, you should call setSummary() when the setting changes to display the current status (such as the Sleep setting shown in figure 5).

Note: As described in the Android Design document about Settings, we recommend that you update the summary for a ListPreference each time the user changes the preference in order to describe the current setting.

For proper lifecycle management in the activity, we recommend that you register and unregister yourSharedPreferences.OnSharedPreferenceChangeListener during the onResume() and onPause()callbacks, respectively:

@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
} @Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}

Caution: When you call registerOnSharedPreferenceChangeListener(), the preference manager does not currently store a strong reference to the listener. You must store a strong reference to the listener, or it will be susceptible to garbage collection. We recommend you keep a reference to the listener in the instance data of an object that will exist as long as you need the listener.

For example, in the following code, the caller does not keep a reference to the listener. As a result, the listener will be subject to garbage collection, and it will fail at some indeterminate time in the future:

不要像下面这样用

prefs.registerOnSharedPreferenceChangeListener(
// Bad! The listener is subject to garbage collection!
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
}
});

Instead, store a reference to the listener in an instance data field of an object that will exist as long as the listener is needed:

SharedPreferences.OnSharedPreferenceChangeListener listener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);

Android偏好设置(6)应用和监听各偏好参数的更多相关文章

  1. Android中Button的五种监听事件

    简单聊一下Android中Button的五种监听事件: 1.在布局文件中为button添加onClick属性,Activity实现其方法2.匿名内部类作为事件监听器类3.内部类作为监听器4.Activ ...

  2. DownEditTextView【自定义Edittext对Android 软键盘向下的监听】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 记录自定义EditText控件实现监听软键盘隐藏事件的功能.基本上和参考资料相同. 效果图    代码分析 自定义EditText子 ...

  3. PIE SDK地图范围设置和图层事件监听

    1. 功能简介 地图范围设置的监听就是通过IMapControlEvents接口对地图的视图范围更新或者地图的分辨率发生变化进行监听,然后做出相应的操作. 图层事件的监听就是通过IActiveView ...

  4. vue同时监听多个参数变化

    computed: { // 同时监听多个参数 toWatch() { const { params1, params2 } = this.observeObj; return { params1, ...

  5. 【Android】[转] Android屏幕旋转使用OrientationEventListener的监听

    说明 遇到一个奇葩的问题,我在使用onConfigChanged拦截屏幕的横竖屏旋转时,发现直接进行180度的横屏/竖屏转换居然没有反应!查找原因发现仅对landscape或者portrait状态有用 ...

  6. Android 多个include标签的监听事件处理

    include标签的作用是为了xml文件代码的模块化,详细不再多提.主要是说说include标签的监听. 网上也有很多例子,不过大多是只写了一个include标签的监听,如果需要实现多个include ...

  7. Android中Preference的使用以及监听事件分析

    在Android系统源码中,绝大多数应用程序的UI布局采用了Preference的布局结构,而不是我们平时在模拟器中构建应用程序时使用的View布局结构,例如,Setting模块中布局.当然,凡事都有 ...

  8. Android几行代码实现实时监听微信聊天

    实现效果: 实时监听当前聊天页面的最新一条消息,如图:            实现原理: 同样是利用AccessibilityService辅助服务,关于这个服务类还不了解的同学可以先看下我上一篇关于 ...

  9. Android电话拦截实现以及TelephonyManager监听的取消

    由于毕业设计题目涉及到电话拦截这一块.所以鼓捣了一下.遇到了一些问题,总结一下,以免忘记,也希望能帮助其他新人们. 本篇博客目的:实现电话的拦截 会遇到的问题:android studio下AIDL的 ...

随机推荐

  1. Pacemaker 安装与使用

    Pacemaker 仅仅做资源管理器(CRM).底下的消息系统採用 corosync. 安装 以 ubuntu 为例, sudo aptitude install -y pacemaker coros ...

  2. 杭电1232畅通project

    畅通project Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  3. Python遇到的零碎小问题

    切记else语句的后面直接加冒号: 字符和数字绝对不能直接相加 对于字符与整数之间的转化 ord('E')可以将其转化为45,chr(65)可以将其转化为A 编写程序的时候尽量要考虑时间复杂度 app ...

  4. 一个IM开源项目LiteTalk

    http://blog.csdn.net/visualwind/article/details/6086631 http://blog.sina.com.cn/s/blog_54b5ea250101n ...

  5. UVa 401 Palindromes(镜像回文字符串)

     题意  给一个字符串 判定其是否为回文串和镜像串  回文串非常好推断  镜像串对于每个字符用数组保存它的镜像字符即可了  没有的就是空格 注意若字符串长度为奇数  中间那个字母必须是对称的才是镜 ...

  6. Kemans算法及其Python 实现

    算法优缺点: 优点:容易实现缺点:可能收敛到局部最小值,在大规模数据集上收敛较慢使用数据类型:数值型数据 算法思想 k-means算法实际上就是通过计算不同样本间的距离来判断他们的相近关系的,相近的就 ...

  7. BC1.2的一些心得

    什么叫DCD DataContact Detect(DCD) 1.首先是DCD 2.然后是Primary detection 3.然后是Secondary detection 检測充电的条件是VBUS ...

  8. Responsive Nav

    引入文件 <!-- 引入这些文件至 <head> 中 --> <link rel="stylesheet" href="responsive ...

  9. I.MX6 各模块 clock 查询

    /********************************************************************* * I.MX6 各模块 clock 查询 * 说明: * ...

  10. Watir: Get document detail information in Watir.

    ie.#{element}(:id,"foo").document.currentstyle.attributeAsCamelCase so ie.#{element}(:id,& ...