直接上代碼緩存
封裝:app
1 //存儲key對應的數據 2 fun saveData(context: Activity, key: String, info: String) { 3 val sharedPreferences = context.getSharedPreferences(key, MODE_PRIVATE) 4 val editor = sharedPreferences.edit() 5 editor.putString(key, info) 6 editor.apply() 7 } 8 9 //取key對應的數據 10 fun getData(context: Activity, key: String): String { 11 val result = context.getSharedPreferences(key, MODE_PRIVATE).getString(key, "") 12 return if (result.isEmpty()) { 13 "" 14 } else { 15 result 16 } 17 } 18 19 //清空緩存對應key的數據 20 fun clearData(context: Activity, key: String) { 21 context.getSharedPreferences(key, MODE_PRIVATE).edit().clear().apply() 22 }
這裏第一個參數傳入Context,方便在各個activity/fragment裏調用this
調用:spa
1 //存數據 2 saveData(this@LoginActivity, "phone", _phone) 3 4 //取數據 5 getData(this, "phone") 6 7 //清除數據 8 clearData(activity!!,"phone")
ps:我這裏都給轉成String封裝了,其實getSharedPreferences什麼類型的都能存code