Android SharedPreferences 存储 key / value 数据
💡
原文中文,约1100字,阅读约需3分钟。
📝
内容提要
SharedPreferences 可以用来保存 Android App 中的默认蓝牙设备 Mac 地址,它提供了读写接口,可以设置 activity 级和 app 级的共享级别,异步写入使用 apply,同步写入使用 commit,数据可能会因为卸载 app、清空 app 数据或者主动调用 editor 的 remove one key 或者 clear 清空所有而消失。
🎯
关键要点
- SharedPreferences 用于保存 Android App 中的默认蓝牙设备 Mac 地址,提供读写接口。
- SharedPreferences 指向一个存储键值对的 XML 文件。
- 共享级别分为 activity 级和 app 级,activity 级使用 getPreferences(),app 级使用 getSharedPreferences() 和 getDefaultSharedPreferences()。
- 异步写入使用 apply,同步写入使用 commit,commit 应避免在 UI 主线程中调用。
- 数据可能因卸载 app、清空 app 数据或主动调用 editor 的 remove 或 clear 而消失。
- 代码示例展示了如何使用 SharedPreferences 存储和读取数据。
- 可以通过 Android Studio 的 Device File Explorer 查看存储的 key/value 数据。
➡️