【问题标题】:How to programatically clear application cache in Android 4.2.2 and above如何以编程方式清除 Android 4.2.2 及更高版本中的应用程序缓存
【发布时间】:2015-01-20 14:26:40
【问题描述】:

在 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'

【问题讨论】:

  • logcat 没有错误?您在哪些设备上出现此行为?
  • to clear my application cash - 你想清除cashcache
  • shkschneider,logcat 中没有错误。设备:三星 Galaxy Tab 2 7.0'
  • @David Wasser,我想从我的 OWN 应用程序代码中清除我的 OWN 应用程序缓存。很遗憾,您提出的解决方案没有奏效。
  • 我故意不在缓存中存储任何内容。我的应用程序包含带有谷歌地图的片段。因此,当我使用应用程序一段时间时,我的应用程序缓存大小会增长到巨大的数量。一段时间后,我想清除我的应用程序缓存。正如我上面所写的,我在 Android 4.0 中这样做没有问题。出于某种原因,我无法清除 Android 4.2.2 中的缓存

标签: java android eclipse google-maps android-sdk-tools


【解决方案1】:

我写这个是为了回答,因为我的评论可能会被埋没。即使我在 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多