package com.example.basecore.util
|
|
import android.annotation.SuppressLint
|
import android.app.Application
|
import android.content.Context
|
import android.content.SharedPreferences
|
import java.io.*
|
|
/**
|
* author: dai
|
* date : 2019-11-23
|
* desc: sp本地存储
|
*/
|
object SPUtils {
|
|
|
|
private lateinit var sp: SharedPreferences
|
|
|
fun initSp( app : Application) {
|
sp = app.getSharedPreferences(
|
"my_sp",
|
Context.MODE_PRIVATE
|
)
|
}
|
|
@SuppressLint("CommitPrefEdits")
|
fun <T> putValue(name: String, value: T) = with(sp.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()
|
}
|
|
@JvmStatic
|
fun getString(key: String, default: String = "-1"): String {
|
return sp.getString(key, default) ?: ""
|
}
|
|
@JvmStatic
|
fun getBoolean(key: String, default: Boolean = false): Boolean {
|
return sp.getBoolean(key, default)
|
}
|
|
@JvmStatic
|
fun getInt(key: String, default: Int = -1): Int {
|
return sp.getInt(key, default)
|
}
|
|
@JvmStatic
|
fun getLong(key: String, default: Long = -1L): Long {
|
return sp.getLong(key, default)
|
}
|
|
|
@JvmStatic
|
fun getFloat(key: String, default: Float = -1f): Float {
|
return sp.getFloat(key, default)
|
}
|
|
/**
|
* 删除全部数据
|
*/
|
fun clearSP() {
|
sp.edit().clear().apply()
|
}
|
|
/**
|
* 根据key删除存储数据
|
*/
|
fun clearSPWithKey(key: String) {
|
sp.edit().remove(key).apply()
|
}
|
|
/**
|
* 序列化对象
|
* @param person
|
* *
|
* @return
|
* *
|
* @throws IOException
|
*/
|
@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
|
}
|
|
/**
|
* 反序列化对象
|
* @param str
|
* *
|
* @return
|
* *
|
* @throws IOException
|
* *
|
* @throws ClassNotFoundException
|
*/
|
@Suppress("UNCHECKED_CAST")
|
@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
|
}
|
|
}
|