【发布时间】:2020-05-12 12:04:32
【问题描述】:
我正在使用EncryptedSharedPreferences在本地存储用户信息(如果您不熟悉,请参阅this)。我已经使用备份规则实现了 AutoBackUp。我备份了首选项,清除了我的应用程序上的数据,并尝试恢复数据(按照for backup 和restore 概述的步骤)。
查看 Android Studio 中的设备文件资源管理器,我可以确认我的 Preferences 文件正在恢复(它已正确命名并且其中包含加密数据)。但是,我的应用程序就像首选项文件不存在一样运行。
我错过了什么?
偏好代码:
class PreferenceManager(context: Context) {
companion object {
private const val KEY_STORE_ALIAS = "APP_KEY_STORE"
private const val privatePreferences = "APP_PREFERENCES"
}
// See https://developer.android.com/topic/security/data#kotlin for more info
private val sharedPreferences = EncryptedSharedPreferences.create(
privatePreferences,
KEY_STORE_ALIAS,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
init {
//val all = sharedPreferences.all
//for (item in all) {
//Log.e("PREFERENCES", "${item.key} - ${item.value}")
//}
}
@SuppressLint("ApplySharedPref")
fun clear() {
// Normally you want apply, but we need the changes to be done immediately
sharedPreferences.edit().clear().commit()
}
fun readBoolean(key: String, defaultValue: Boolean): Boolean {
return sharedPreferences.getBoolean(key, defaultValue)
}
fun readDouble(key: String): Double {
return sharedPreferences.getFloat(key, 0f).toDouble()
}
fun readString(key: String): String {
return sharedPreferences.getString(key, "")!!
}
fun removePreference(key: String) {
sharedPreferences.edit().remove(key).apply()
}
fun writeBoolean(key: String, value: Boolean) {
sharedPreferences.edit().putBoolean(key, value).apply()
}
fun writeDouble(key: String, value: Double) {
sharedPreferences.edit().putFloat(key, value.toFloat()).apply()
}
fun writeString(key: String, value: String) {
sharedPreferences.edit().putString(key, value).apply()
}
}
我目前没有实施 BackupAgent。
【问题讨论】:
标签: android kotlin sharedpreferences backup restore