avatar🐀
霂枯木霂枯木的小站

To witness the sunrise and the sea of blossoms.

行可兼知,而知不可兼行

SharePreference

介绍 ​

键值对存储,xml形式,适合简单配置。

存储位置
/data/data/<包名>/shared_prefs/<文件名>.xml
xml示例
xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="username">zhangsan</string>
    <boolean name="isLogin" value="true" />
    <int name="age" value="18" />
</map>

保存 ​

kotlin
val sp = context.getSharedPreferences("app_settings", Context.MODE_PRIVATE)
kotlin
sp.edit()
    .putInt("launch_count",1)
    .putString("name","tim")
    .putBoolean("isDark",true)
    .apply()

注:apply是立即更新,磁盘写入异步。commit同步写入。

读取 ​

kotlin
val launchCount = sp.getInt("launch_count",0)
val name = sp.getString("name","")
val isDark = sp.getBoolean("isDark",false)
val timestamp = sp.getLong ("timestamp",System.currentTimeMillis())

删除 ​

kotlin
sp.edit().remove("launch_count").apply()
sp.edit().clear().apply()

监听变化 ​

kotlin
listener = SharedPreferences.OnSharedPreferenceChangeListener{
    preferences, keys ->
    if (keys == "isDark"){

    }
}

注:监听对象要保持引用,注意回收

datastore
由 Valaxy v1.2.0 驱动|主题-Yunv1.2.0