import android.text.TextUtils
import com.chiquedoll.chiquedoll.utils.MmkvUtil
import com.chiquedoll.chiquedoll.utils.isEmptyNoBlank
/***
* 保存有过期时间的mmkv
* 2022年4月7日 14:17:59
* auth:Bill liang
* e-mail:ls9421@vip.qq.com
* 优化
*/
class AcacheUtils {
companion object {
private val mSeparator = "卍"
private val mDataSeparator = "-"
/***
* 保存string类型的数据
* @param key key值
* @param value:值
* @param saveTime: 保存时长
*/
fun saveMmkvAcache(key: String, value: String, saveTime: Int) {
MmkvUtil.encode(key, newStringWithDateInfo(saveTime, value))
}
/****
*获取数据
* @param key
* @param 有效的默认值
* @param 失效的默认值
*/
fun getMmkvAcache(key: String, default: String = "", lostStr: String = ""): String {
var strList =
getDateInfoFromDate(MmkvUtil.decodeString(key, default), mSeparator, mDataSeparator)
if (isDue(strList)) {
//过期了
return lostStr
} else {
if (strList != null && strList.size > 2) {
return isEmptyNoBlank(strList[2])
} else {
return default
}
}
}
/****
* 判断是否过期
*/
private fun isDue(dataList: ArrayList<String>?): Boolean {
if (!dataList.isNullOrEmpty()) {
if (dataList.size > 2) {
try {
return System.currentTimeMillis() > (dataList[0].toLong() + ((dataList[1].toLong()) * 1000))
} catch (e: Exception) {
return true
}
} else {
return true
}
} else {
return true
}
}
/***
* 需要保存的值
*/
private fun newStringWithDateInfo(second: Int, strInfo: String): String {
return System.currentTimeMillis()
.toString() + mDataSeparator + second + mSeparator + strInfo
}
/***
* 获取第一个万字符
*/
private fun indexOf(data: String?, cData: String?): Int {
var currentIndex = -1
if ((!TextUtils.isEmpty(data)) && (!TextUtils.isEmpty(cData))) {
for ((index, dataStr) in data!!.withIndex()) {
if ((dataStr.toString()).equals(cData)) {
currentIndex = index
break
}
}
}
return currentIndex;
}
/***
* 获取三个数据
*/
private fun getDateInfoFromDate(
mData: String?,
mSeparator: String,
mDataSeparator: String
): ArrayList<String>? {
var saveDate: String? = null
var deleteAfter: String? = null
var realSaveStr: String? = null
if (TextUtils.isEmpty(mData)) {
return null
} else {
var dataList = ArrayList<String>()
var indexOf = indexOf(mData, mDataSeparator)
var indextOfDelete = indexOf(mData, mSeparator)
if (indexOf == -1 || indextOfDelete == -1 || (indexOf >= indextOfDelete)) {
return null
}
if (mData!!.length > indexOf) {
saveDate = mData.substring(0, indexOf)
} else {
saveDate = ""
}
if (mData.length > indextOfDelete) {
deleteAfter = mData.substring(indexOf + 1, indextOfDelete)
} else {
deleteAfter = ""
}
if (mData.length > indextOfDelete + 1) {
realSaveStr = mData.substring(indextOfDelete + 1, mData.length)
} else {
realSaveStr = ""
}
dataList.add(saveDate)
dataList.add(deleteAfter)
dataList.add(realSaveStr)
return dataList
}
}
}
}
需要永久储存化,但是必须要设置过期时间的数据如何处理?
最新推荐文章于 2023-08-24 11:22:36 发布