【问题标题】:programmatically clear image cache in android以编程方式清除android中的图像缓存
【发布时间】:2015-02-24 18:59:34
【问题描述】:

我想清除我的 android 应用程序中的缓存,为了实现这一点,我使用了下面给出的两种方法,但是在调用 deleteCache(getApplicationContext()) 后缓存没有被清除。这个问题被多次问到,但似乎没有一个答案对我有帮助。以下是我使用的方法。感谢您的帮助。

public static void deleteCache(Context context) {

    try {

        File dir = context.getCacheDir();

        if (dir != null && dir.isDirectory()) {

            deleteDir(dir);
        }

    } catch (Exception e) {}
}

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();
}

【问题讨论】:

  • 是logcat中显示的错误吗?还是返回 false?
  • 感谢 Randyka,logcat 中没有显示错误,它返回 true。

标签: android caching


【解决方案1】:

由于您没有提及您面临的任何特定日志或问题,[“不工作”不是一个特定问题 :)]

试试这个 -

private void deleteRecursive(File fileOrDirectory) {

        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                deleteRecursive(child);

        fileOrDirectory.delete();

    }
// from the point you want to clear-

deleteRecursive(context.getCacheDir());

【讨论】:

  • 嗨阿米特,当我说它不起作用时,我的意思是缓存没有被清除并且我没有遇到任何错误。非常感谢,但您的解决方案也没有帮助。顺便说一句,如果此信息很重要,我会将图像放在 DiskLruCache 上。
  • 您是否使用任何特定的图像加载库? @Fissehaye,您能分享一下您是如何使用 DISkLruCache 存储图像的吗?一般来说,要清除 DiskLruCache 调用“delete()”是不够的,我们需要调用“deleteContents()”
  • 确保您在 DiskLruCache 中使用 context.getCacheDir()。否则,请清除您在 DiskLruCache 路径中设置的目录。我相信您需要发布您的图像缓存代码以进一步检测特定问题。
猜你喜欢
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
相关资源
最近更新 更多