在 Android 4.0 中,我使用此解决方案来清除我的应用程序缓存,并且效果完美:
public void clearApplicationData()
{
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
}
}
}
}
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();
}
不幸的是,这个解决方案在 4.2.2 Android 版本中不起作用(也可能在以上 Android 版本中起作用)。有人知道为什么吗?也许还有另一种方法可以清除缓存?
我特别对谷歌地图缓存清除感兴趣,上面写的解决方案适用于我的 Android 4.0,但不适用于 Android 4.2.2。任何帮助将不胜感激。
我在 logcat 中没有收到任何错误。设备:三星 Galaxy Tab 2 7.0'
最佳答案
我写这篇文章作为答案,因为我的评论可能会被埋没。即使我在 4.2.2 设备中清除缓存时也遇到了麻烦,这段代码由 David Wasser 在 post 中编写。为我工作。
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024;
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
关于java - 如何在 Android 4.2.2 及更高版本中以编程方式清除应用程序缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28047757/