我想在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();
}
答案 0 :(得分:0)
在清单中添加以下权限:
<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
}
}