[英]How to programatically clear application cache in Android 4.2.2 and above
在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版本中)也不起作用。 有人知道為什么嗎? 也許還有另一種清除緩存的方法?
我對Google地圖緩存的清除特別感興趣,並且上面編寫的解決方案對我適用於Android 4.0,但不適用於Android 4.2.2。 任何幫助,將不勝感激。
我在logcat中沒有任何錯誤。 設備:三星Galaxy Tab 2 7.0'
我將其寫為答案,因為我的評論可能會被掩埋。 即使我有麻煩在4.2.2設備的代碼由David瓦瑟在此清除緩存后為我工作。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.