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. Shell 脚本小试牛刀(5) -- 超便捷脚本之高速ssh 登录其它主机

    假设你也是以Linux 为工作环境的童鞋,那么此文真是捷报!由于我的学习/工作中(特别是近期玩耍树莓派)常常会使用到ssh 登录其它主机,而每次使用ssh 登录都须要输入老长一大串让我非常烦.所以我写 ...

  2. C#结构类型图

    C#结构类型图     分类: C#

  3. The type java.lang.reflect.AnnotatedElement cannot be resolved. It is indirectly referenced from required .class files

    我这个错误发生于导入项目的时候..我发现主要是jdk版本的问题.切换一下jdk.直接红叉消失就可以了.....jdk版本一致性还是很重要的

  4. Thinking in Java -- 类型信息RTTI

    Thinking in Java – 类型信息 个人感觉 java 中的比較难的部分了,在看了些netty源代码发现事实上这块很实用. 这章重点是RTTI和反射.先说下自己的理解 RTTI是执行时识别 ...

  5. browser user agent

    乐视X501 UC浏览器1080x1920x32Mozilla/5.0 (Linux; U; Android 5.0.2; zh-CN; Letv X501 Build/DBXCNOP55013041 ...

  6. css3动画应用-音乐唱片旋转播放特效

    css3动画应用-音乐唱片旋转播放特效 核心点: 1.设置图片为圆形居中,使图片一直不停旋转. 2.文字标题(潘玮柏--反转地球)一直从左到右不停循环移动. 3.点击图标,音乐暂停,图片停止旋转:点击 ...

  7. Node.js 101(2): Promise and async

    --原文地址:http://blog.chrisyip.im/nodejs-101-package-promise-and-async 先回想一下 Sagase 的项目结构: lib/ cli.js ...

  8. mybatis_2

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...

  9. Apache POI组件操作Excel,制作报表(三)

    Apache POI组件操作Excel,制作报表(三) 博客分类: 探索实践 ExcelApache算法Office单元测试      上一篇介绍了POI组件操作Excel时如何对单元格和行进行设置, ...

  10. UITabBarController简单介绍

    一.简单介绍 UITabBarController和UINavigationController类似,UITabBarController也可以轻松地管理多个控制器,轻松完成控制器之间的切换,典型的例 ...