SharedPreferences共享首选项

这是一个轻量及的键值存储机制,只能够存储基本数据类型,以KEY-VALUES存储
java

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.api

建立一个指定名称的SP
app

getPreferences()  - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.异步

不指定名称成绩一个只能在该Activity下试用的SP
ide

// 建立SharedPreferences得对象
// MODE_PRIVATE 这是默认的形式,配置文件只容许本程序和享有本程序ID的程序的访问
// MODE_WORLD_READABLE 容许其余的应用程序读文件
// MODE_WORLD_WRITEABLE 容许其余的应用程序写文件
// 该状态在api23已废弃
// MODE_MULTI_PROCESS 主要用于多任务,2.3版本当多个进程共同访问的时候,必须指定这个标签
SharedPreferences sp = getSharedPreferences("SP_NAME", Activity.MODE_PRIVATE);
// 取值
sp.getString("key", "若是为空,所显示的默认值");
// 得到编辑对象
SharedPreferences.Editor editor = sp.edit();
// 设置值
editor.putString("key", "value");
// 提交当两个编辑提交时后者的提交将覆盖前者,前者将返回false。若是不关心返回值的话可以使用apply
editor.commit();

commit直接同步提交到磁盘,apply则先提交到内存而后在异步提交到磁盘,apply提交将不会提示失败因此若是不关心保存是否成功的话使用applythis


版权声明:本文为博主原创文章,未经博主容许不得转载。code

相关文章
相关标签/搜索