通用图片加载器 - 手动清除缓存

8
我正在使用通用图像加载器在我的应用程序中显示列表视图中的图像。根据文档,我正在使用UnlimitedDiscCache,因为这是最快的缓存机制。
然而,在我的应用程序关闭时(例如,在onStop()中),我想清除磁盘缓存,但只删除超过给定限制的最老缓存文件(就像TotalSizeLimitedDiscCache一样)。
我知道ImageLoader.clearDiscCache(),但在我的情况下,这将清除整个缓存,因为我之前使用了UnlimitedDiscCache...
所以,当用户加载和滚动列表视图时,我想拥有最快的缓存机制,并在用户不再与应用程序交互时进行缓慢的缓存清除。
有什么想法如何实现这一点吗?

当调用onStop()方法时,无法保证应用程序已经停止。这只是说明当前活动正在停止。与实现另一个缓存机制(可能会减慢应用程序)所花费的时间相比,性能损失非常小。 - Austyn Mahoney
@jeff_bordon 你有用于构建ImageLoader实例的任何代码吗? @Androidy 是的,你可以区分应用程序即将完成的时候,比如 if(isFinishing()) { do something} - Nikola Despotoski
@jeff_bordon 你可以拥有BoB(最佳两者)。在这里查看源代码 https://github.com/nostra13/Android-Universal-Image-Loader/blob/master/library/src/com/nostra13/universalimageloader/cache/disc/impl/LimitedAgeDiscCache.java编写UnlimitedAgeDiskCache将非常简单。你只需要知道日期和现在与之间的差异即可。我认为如果只是几个if语句,它不会降低ListViews的速度。 - Nikola Despotoski
isFinishing() 只能告诉你当前的 Activity 是否停止,而不能判断整个应用是否停止。如果你只使用一个 Activity,那么可以使用该方法,但是如果有多个 Activity,则会出现问题。 - Austyn Mahoney
2个回答

1

从这里查看https://dev59.com/-2445IYBdhLWcg3wcZ4N#7763725 可能会对你有所帮助。

@Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}


public static void trimCache(Context context) {
try {
    File dir = context.getCacheDir();
    if (dir != null && dir.isDirectory()) {
        deleteDir(dir);

    }
} catch (Exception e) {
    // TODO: handle exception
}
}


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

// <uses-permission
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
// The directory is now empty so delete it

return dir.delete();
}

0
如果您想要清除内存中的缓存,可以使用以下代码:
MemoryCacheUtils.removeFromCache(imageUri, ImageLoader.getInstance().getMemoryCache());

如果您还想清除磁盘中的缓存,可以使用以下代码:
DiscCacheUtils.removeFromCache(imageUri, ImageLoader.getInstance().getDiscCache());

这是一种更简单的清除缓存的方法。 您可以在此线程中找到类似的答案:

如何使用Universal Image Loader Android强制清除缓存?

希望这些信息有所帮助。 :)


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