1、代码
package com.example.myapplication.utils
import android.content.Context
import android.content.SharedPreferences
import com.example.myapplication.App
import java.io.*
import kotlin.reflect.KProperty
class Preference<T>(val name: String, private val default: T) {
companion object {
private val prefs: SharedPreferences by lazy {
App.context.getSharedPreferences("sp_file_name", Context.MODE_PRIVATE)
}
fun clearSP() {
prefs.edit().clear().apply()
}
fun clearSP(key: String) {
prefs.edit().remove(key).apply()
}
fun contains(key: String): Boolean {
return prefs.contains(key)
}
fun getAll(): Map<String, *> {
return prefs.all
}
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return getSharePreferences(name, default)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putSharedPreferences(name, value)
}
private fun putSharedPreferences(name: String, value: T) = with(prefs.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> putString(name, serialize(value))
}.apply()
}
private fun getSharePreferences(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> deSerialization(getString(name, serialize(default)))
}
return res as T
}
@Throws(IOException::class)
private fun <A> serialize(obj: A): String {
val byteArrayOutputStream = ByteArrayOutputStream()
val objectOutputStream = ObjectOutputStream(byteArrayOutputStream)
objectOutputStream.writeObject(obj)
var serStr = byteArrayOutputStream.toString("ISO-8859-1")
serStr = java.net.URLEncoder.encode(serStr, "UTF-8")
objectOutputStream.close()
byteArrayOutputStream.close()
return serStr
}
@Throws(IOException::class, ClassNotFoundException::class)
private fun <A> deSerialization(str: String): A {
val redStr = java.net.URLDecoder.decode(str, "UTF-8")
val byteArrayInputStream = ByteArrayInputStream(redStr.toByteArray(charset("ISO-8859-1")))
val objectInputStream = ObjectInputStream(byteArrayInputStream)
val obj = objectInputStream.readObject() as A
objectInputStream.close()
byteArrayInputStream.close()
return obj
}
}
2、使用
class App : Application() {
companion object {
var context: Context by Delegates.notNull()
private set
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
}
private var userName: String by Preference("user_name", "")