单例配合sharedpreference实现存储密码:
// 私有化构造方法
class sharePrefre private constructor(){
private val FILE_NAME = "passward"
private val KEY = "passwardKey"
// 伴生对象
companion object{
private var instant: sharePrefre? = null
private var mContext:Context? = null
fun getInstance(context: Context):sharePrefre{
mContext = context
if (instant == null){
instant = sharePrefre()
}
return instant!!
}
}
// 保存密码
fun savePassward(passward: String){
mContext?.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE).also {
it?.edit().also {
it?.putString(KEY,passward)
it?.apply()
}
}
}
// 获取密码
fun getPassward():String?{
mContext?.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE).also {
return it?.getString(KEY,null)
}
}
}
调用:
rPassward = sharePrefre.getInstance(this).getPassward()
sharePrefre.getInstance(this).savePassward(firstParssward!!)
网友评论