Skip to content

Commit a8d926e

Browse files
committed
feat: 缓存清理开放
1 parent 3f4ef1a commit a8d926e

File tree

1 file changed

+56
-10
lines changed

1 file changed

+56
-10
lines changed

library/src/main/java/com/opensource/svgaplayer/SVGACache.kt

Lines changed: 56 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,33 @@
11
package com.opensource.svgaplayer
22

33
import android.content.Context
4+
import com.opensource.svgaplayer.utils.log.LogUtils
45
import java.io.File
56
import java.net.URL
67
import java.security.MessageDigest
78

8-
9+
/**
10+
* SVGA 缓存管理
11+
*/
912
object SVGACache {
1013
enum class Type {
1114
DEFAULT,
1215
FILE
1316
}
1417

18+
private const val TAG = "SVGACache"
1519
private var type: Type = Type.DEFAULT
1620
private var cacheDir: String = "/"
21+
get() {
22+
if (field != "/") {
23+
val dir = File(field)
24+
if (!dir.exists()) {
25+
dir.mkdirs()
26+
}
27+
}
28+
return field
29+
}
30+
1731

1832
fun onCreate(context: Context?) {
1933
onCreate(context, Type.DEFAULT)
@@ -27,22 +41,54 @@ object SVGACache {
2741
this.type = type
2842
}
2943

30-
// fun clearCache(context: Context?){
31-
// context ?: return
32-
// cacheDir = "${context.cacheDir.absolutePath}/svga/"
33-
// File(cacheDir).takeIf { it.exists() }?.delete()
34-
// }
44+
/**
45+
* 清理缓存
46+
*/
47+
fun clearCache() {
48+
if (!isInitialized()) {
49+
LogUtils.error(TAG, "SVGACache is not init!")
50+
return
51+
}
52+
SVGAParser.threadPoolExecutor.execute {
53+
clearDir(cacheDir)
54+
LogUtils.info(TAG, "Clear svga cache done!")
55+
}
56+
}
57+
58+
// 清除目录下的所有文件
59+
private fun clearDir(path: String) {
60+
try {
61+
val dir = File(path)
62+
dir.takeIf { it.exists() }?.let { parentDir ->
63+
parentDir.listFiles()?.forEach { file ->
64+
if (!file.exists()) {
65+
return@forEach
66+
}
67+
if (file.isDirectory) {
68+
clearDir(file.absolutePath)
69+
}
70+
file.delete()
71+
}
72+
}
73+
} catch (e: Exception) {
74+
LogUtils.error(TAG, "Clear svga cache path: $path fail", e)
75+
}
76+
}
3577

3678
fun isInitialized(): Boolean {
37-
return "/" != cacheDir&&File(cacheDir).exists()
79+
return "/" != cacheDir && File(cacheDir).exists()
3880
}
3981

4082
fun isDefaultCache(): Boolean = type == Type.DEFAULT
4183

4284
fun isCached(cacheKey: String): Boolean {
43-
return (if (isDefaultCache()) buildCacheDir(cacheKey) else buildSvgaFile(
44-
cacheKey
45-
)).exists()
85+
return if (isDefaultCache()) {
86+
buildCacheDir(cacheKey)
87+
} else {
88+
buildSvgaFile(
89+
cacheKey
90+
)
91+
}.exists()
4692
}
4793

4894
fun buildCacheKey(str: String): String {

0 commit comments

Comments
 (0)