如图清理缓存的功能是App中经常需要做的一个功能
缓存主要计算的是
1.安卓内置数据库中的数据对应 data/data/应用包名/databases/数据库名称 路径下的数据内容
2.图片加载框架中图片的磁盘缓存
3.SharePrefenerce中一些简单的基本类型的数据存储
暂时只知道这些。
缓存计算主要就是计算对应缓存文件的大小code如下:
fun getFolderSize(file: File): Long {
var size: Long = 0
try {
val fileList = file.listFiles()
for (aFileList in fileList) {
if (aFileList.isDirectory) size += getFolderSize(aFileList) else {
size += aFileList.length()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return size
}
传入要计算的File得到对应的字节一般需要展示的单位是M,方法转换如下:
fun getPrintSize(s: Long): String {
var size = s.toFloat()
if (size < 1024) {
return save2float(size) + "B" + ")"
} else {
size /= 1024
}
if (size < 1024) {
return save2float(size) + "K" + ")"
} else {
size /= 1024
}
if (size < 1024) {
return save2float(size) + "M" + ")"
} else {
size /= 1024
}
return save2float(size) + "G" + ")"
}
private fun save2float(n: Float): String {
return "(" + (Math.round(n * 100).toFloat() / 100).toString()
}
以上方法可以获取到缓存大小。
清理缓存无非就是删除对应缓存文件方法如下:
private fun clearCache(): Boolean {
doAsync {
val glideCacheDir = Glide.getPhotoCacheDir(this@MainActivity) as File
var totalSize: Long = getFolderSize(glideCacheDir)
totalSize += getFolderSize(App.instance.cacheDir)
uiThread {
if (totalSize == 0L) {
item.title = "清理完成"
return@uiThread
}
item.title = "正在清理${getPrintSize(totalSize)}..."
doAsync {
deleteFolderFile(object : FileUtil.Companion.DeleteListener {
override fun onDone() {
uiThread {
item.title = "清理完成"
}
}
override fun onDelete(size: Long) {
uiThread {
totalSize -= size
}
}
}, glideCacheDir, App.instance.cacheDir)
}
}
}
return true
}
对应FileUtil中方法:
//监听数据清除的过程及时修改缓存大小的监听
interface DeleteListener {
fun onDelete(size: Long)
fun onDone()
}
fun deleteFolderFile(deleteListener: DeleteListener,vararg dirs: File ) {
for ( dir in dirs){
try {
val fileList = dir.listFiles()
for (aFileList in fileList!!) {
if (aFileList.isDirectory) {
deleteFolderFile(deleteListener, aFileList)
} else {
deleteListener.onDelete(deleteFileS(aFileList))
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
deleteListener.onDone()
}
private fun deleteFileS(file: File): Long {
val size = file.length()
file.delete()
return size
}