1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| import android.content.Context import android.content.SharedPreferences
object SPUtil { private lateinit var sp: SharedPreferences
const val FILE_NAME: String = "share_data"
fun init(context: Context) { sp = context.getSharedPreferences(SPUtil.FILE_NAME, Context.MODE_PRIVATE); }
fun putString(key: String, value: String) { checkInit() sp.edit().putString(key, value).apply() }
fun getString(key: String, defaultValue: String = ""): String { checkInit() return sp.getString(key, defaultValue) ?: defaultValue }
fun putInt(key: String, value: Int) { checkInit() sp.edit().putInt(key, value).apply() }
fun getInt(key: String, defaultValue: Int = 0): Int { checkInit() return sp.getInt(key, defaultValue) }
fun putBoolean(key: String, value: Boolean) { checkInit() sp.edit().putBoolean(key, value).apply() }
fun getBoolean(key: String, defaultValue: Boolean = false): Boolean { checkInit() return sp.getBoolean(key, defaultValue) }
fun putFloat(key: String, value: Float) { checkInit() sp.edit().putFloat(key, value).apply() }
fun getFloat(key: String, defaultValue: Float = 0f): Float { checkInit() return sp.getFloat(key, defaultValue) }
fun putLong(key: String, value: Long) { checkInit() sp.edit().putLong(key, value).apply() }
fun getLong(key: String, defaultValue: Long = 0L): Long { checkInit() return sp.getLong(key, defaultValue) }
fun remove(key: String) { checkInit() sp.edit().remove(key).apply() }
fun clear() { checkInit() sp.edit().clear().apply() }
private fun checkInit() { if (!::sp.isInitialized) { throw IllegalStateException("SPUtil 尚未初始化,请先在Application中调用 init() 方法") } } }
|