如何清除 Android 缓存

17

我需要找到一种清除应用程序缓存数据的方法。基本上,我正在使用Fedor(ListView中图像的延迟加载)的惰性列表实现,并且当加载了100张图片时,我希望自动清除缓存。有什么想法吗?

编辑: 代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    list=(ListView)findViewById(R.id.list);
    adapter=new LazyAdapter(this, mStrings);
    list.setAdapter(adapter);

    deleteCache(this);
    adapter.notifyDataSetChanged();


}

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

你好,你有答案吗?我和你遇到了同样的问题。我想清除缓存以加载新的图片。谢谢! - Huy Tower
6个回答

38

这将删除缓存

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

你如何知道缓存是否已被删除? - ilango j
因为我认为如果缓存被删除,图片将重新开始加载,但它们并没有。这是我想要实现的目标。 - hardartcore
很抱歉,但我无法让这个东西工作。我相当肯定我错过了一些微小而愚蠢的东西,但是... - hardartcore
我更新了问题并附上了我正在使用的代码,但仍然看不到重新加载... - hardartcore
1
请注意,如果您使用外部缓存,您需要将 context.getCacheDir() 替换为 context.getExternalCacheDir() - Eran Goldin
显示剩余6条评论

4
我希望这能帮助你更进一步。
public static void trimCache(Context context) {
    File dir = context.getCacheDir();
    if(dir!= null && dir.isDirectory()){
        File[] children = dir.listFiles();
        if (children == null) {
            // Either dir does not exist or is not a directory
        } else {
            File temp;
            for (int i = 0; i < children.length; i++) {
                temp = children[i];
                temp.delete();
            }
        }

    }

} 

1
请勿在您的帖子中添加标语或签名。您的名字和指向您个人资料的链接将自动显示在您编写的每个问题或答案的底部。 - Tim Post

2

您可以调用系统服务 clearApplicationUserData()(仅适用于 >= KitKat 版本),这将清除应用程序的用户数据。

因此,您可以检查版本,然后一切都会很好 :) 以下是代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ((ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE))
                    .clearApplicationUserData();
    }

欢迎来到StackOverflow!除了为使用KitKat或更高版本的用户提供信息外,请还包括为使用较低版本的用户提供信息。 - buczek
实际上,这部分代码完全导致了我的应用程序崩溃。 - Borzh
这个方法是用来清除应用程序的所有数据,而不是应用程序的缓存!根据这个答案,预计应用程序将关闭,因为此方法完全重置了应用程序,所以应用程序不需要运行... - Kevin Vuilleumier

0

使用 Kotlin,您只需调用

File(context.cacheDir.path).deleteRecursively()

与其他答案相同的结果,但无需手动进行检查和循环。

0
如果使用Apache Commons IO,您可以用一行代码(不包括try-catch)完成此操作:
try {
    FileUtils.deleteDirectory(context.getCacheDir());
} catch (IOException e) {
    // Do some error handling
}

-4

丢弃旧的适配器并将ListView附加到新的适配器实例上(尽管ListView将失去滚动位置)。例如:

    @Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    m_adapter = new MyAdapter(this);
        final ListView listView = (ListView) getView()
                .findViewById(R.id.my_list);
        listView.setAdapter(m_adapter);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接