gpt4 book ai didi

android - 如何在 Marshmallow 中以编程方式清除应用程序缓存

转载 作者:太空狗 更新时间:2023-10-29 14:46:12 26 4
gpt4 key购买 nike

我想在 Android Marshmallow 6.0 中以编程方式清除我的应用程序缓存。我尝试了以下代码,但它在 Marshmallow 中不起作用。我在堆栈溢出中读到以下代码已从 API 级别 19 开始弃用。我在我的 Manifests.xml 中添加了 CLEAR_APP_CACHE 权限

 public  void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}

public 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;
}
}
}

// The directory is now empty so delete it
return dir.delete();
}

最佳答案

在您的 list 中添加以下权限:

<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />

您还应该检查外部缓存目录。

public  void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
File exDir = context.getExternalCacheDir();
if (exDir != null && exDir.isDirectory()) {
deleteDir(exDir);
}
} catch (Exception e) {
// TODO: handle exception
}
}

关于android - 如何在 Marshmallow 中以编程方式清除应用程序缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39991047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com