Android SharedPreferences四种操作模式使用详解
作者:七色音阶 时间:2021-06-06 00:15:08
Android SharedPreferences详解
获取SharedPreferences的两种方式:
1 调用Context对象的getSharedPreferences()方法
2 调用Activity对象的getPreferences()方法
两种方式的区别:
调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一应用程序下的其他组件共享.
调用Activity对象的getPreferences()方法获得的SharedPreferences对象只能在该Activity中使用.
SharedPreferences的四种操作模式:
Context.MODE_PRIVATE
Context.MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取。
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
将数据保存至SharedPreferences:
SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
String name="xixi";
String age="22";
editor.putString("name", name);
editor.putString("age", age);
editor.commit();
从SharedPreferences读取数据:
SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("name", "defaultname");
String age=preferences.getString("age", "0");
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!大家如果有疑问请留言或者到本站社区交流讨论,共同进步!
标签:Android,SharedPreferences
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
android保存Bitmap图片到指定文件夹示例
2022-10-11 22:59:14
初识Spring Boot框架和快速入门
2022-10-17 00:58:52
![](https://img.aspxhome.com/file/2023/2/97932_0s.png)
java反射深入剖析(推荐)
2022-10-10 18:50:35
![](https://img.aspxhome.com/file/2023/7/113487_0s.jpg)
Java中的接口多继承机制
2023-08-28 06:13:48
![](https://img.aspxhome.com/file/2023/4/79824_0s.png)
C++实现经典24点纸牌益智游戏
2023-04-22 01:05:02
![](https://img.aspxhome.com/file/2023/0/109780_0s.jpg)
Spring中Bean的三种实例化方式详解
2023-07-28 12:37:07
![](https://img.aspxhome.com/file/2023/5/88145_0s.png)
C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法
2023-07-18 17:20:29
java在网页上面抓取邮件地址的方法
2023-10-01 19:18:21
Flutter进阶之实现动画效果(三)
2023-01-26 05:12:49
![](https://img.aspxhome.com/file/2023/8/118968_0s.gif)
js 交互在Flutter 中使用 webview_flutter
2023-07-20 22:40:14
![](https://img.aspxhome.com/file/2023/5/91785_0s.jpg)
IntelliJ IDEA安装插件阿里巴巴Java开发手册(Alibaba Java Coding Guidelines)
2023-10-17 11:30:02
![](https://img.aspxhome.com/file/2023/3/113443_0s.png)
Android简单实现文件下载
2023-08-28 06:33:17
C语言数据结构之二叉树详解
2021-08-18 20:56:41
![](https://img.aspxhome.com/file/2023/3/120783_0s.png)
详解android 人脸检测你一定会遇到的坑
2023-03-10 15:24:34
![](https://img.aspxhome.com/file/2023/1/118951_0s.jpg)
C# char类型字符转换大小写的实现代码
2021-07-27 19:21:09
java设计模式--三种工厂模式详解
2023-11-29 09:54:06
![](https://img.aspxhome.com/file/2023/7/60337_0s.png)
Java中Spring Boot+Socket实现与html页面的长连接实例详解
2022-12-24 12:06:12
![](https://img.aspxhome.com/file/2023/1/85401_0s.png)
springboot加载复杂的yml文件获取不到值的解决方案
2021-07-29 18:26:11
Android编程创建桌面快捷方式的常用方法小结【2种方法】
2023-12-07 00:50:35
Springboot整合Freemarker的实现详细过程
2023-01-23 22:09:57
![](https://img.aspxhome.com/file/2023/4/84164_0s.jpg)