如果您按照 Kotlin 示例所述,创建了类似于 https://exoplayer.dev/downloading-media.html 中描述的缓存文件夹。
@Synchronized
fun getDownloadCache(): Cache {
if (downloadCache == null) {
val downloadContentDirectory = File(getDownloadDirectory(), DOWNLOAD_CONTENT_DIRECTORY)
downloadCache = SimpleCache(downloadContentDirectory, NoOpCacheEvictor(), getDatabaseProvider())
}
return downloadCache as Cache
}
您可以在代码中的任何地方轻松访问此缓存来执行此操作。
fun clearCache() {
application.getDownloadCache().release()
}
或者用以下方法清除单个键:
fun removeKeyFromCache(key: String) {
CacheUtil.remove(application.getDownloadCache(), key)
}
应用程序是您的应用程序的一个实例,可以像这样创建
lateinit var singleton: MyApp
open class MyApp: Application() {
override fun onCreate() {
super.onCreate()
singleton = this
}
}
并且可以从任何地方访问它:
private val application: MyApp = singleton
对我来说它正在工作:
public static void clearVideoCache(Context context){
try {
File dir = new File(context.getCacheDir(), cacheFolder);
deleteDir(dir);
} catch (Exception e) { e.printStackTrace();}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
完整代码:
public class VideoCache {
private static final String cacheFolder = "exoCache";
private static SimpleCache sDownloadCache;
public static SimpleCache getInstance(Context context) {
if (sDownloadCache == null) sDownloadCache = new SimpleCache(new File(context.getCacheDir(), cacheFolder), new LeastRecentlyUsedCacheEvictor(2000 * 1024 * 1024), new ExoDatabaseProvider(context));
return sDownloadCache;
}
public static void clearVideoCache(Context context){
try {
File dir = new File(context.getCacheDir(), cacheFolder);
deleteDir(dir);
} catch (Exception e) { e.printStackTrace();}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
}
您可以通过访问保存缓存的目录来实现这一点,这样可以在OnDestroy方法中完成。希望我能帮到您。
JAVA
File file = new File(mContext.cacheDir, "NameFolder")
file.delete()
KOTLIN
val file = File(mContext.getCacheDir(), "NameFolder")
file.delete()
key
是什么有些困惑,不过我发现静态函数将在CacheUtil
中生成key
:CacheUtil.generateKey(Uri.parse("www.test.com/1.mp3"))
- Abed