如何在Android中获取缓存大小

6
我在我的测试应用程序中使用了fedor的懒加载列表实现,其中我可以通过单击一个按钮来清除缓存。如何获取ListView中已加载图像的缓存大小并以编程方式清除缓存?
以下是保存缓存图像的代码:
public ImageLoader(Context context){
    //Make the background thead low priority. This way it will not affect the UI performance.
    photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
    mAssetManager = context.getAssets();

    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
    else
        cacheDir = context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

编辑:

所以基本上我在clearCache()方法中添加了这段代码,但是当我滚动时,我仍然看不到图片重新开始加载。

public void clearCache() {
    //clear memory cache

    long size=0;
    cache.clear();

    //clear SD cache
    File[] files = cacheDir.listFiles();
    for (File f:files) {
        size = size+f.length();
        if(size >= 200)
            f.delete();
    }
}
4个回答

7

要查找缓存目录的大小,请使用以下代码。

public void clearCache() {
    //clear memory cache

    long size = 0;
    cache.clear();

    //clear SD cache
    File[] files = cacheDir.listFiles();
    for (File f:files) {
        size = size+f.length();
        f.delete();
    }
}

这将返回字节数。

我刚刚编辑了我的问题,并附上了我现在使用的代码,但是仍然无法看到滚动后加载的图像。 - Android-Droid
你在哪里调用了清除缓存的功能?为什么你要在 if(size>=200) 的情况下执行代码 f.delete() - ilango j
我在我的主活动中这样调用:adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); 。我加了IF语句,因为我想在缓存大小达到200kb时删除缓存。我这样做对吗? - Android-Droid
好的,我该如何调用那段代码以清除200kb大小的缓存? - Android-Droid
使用上面的代码。我认为那可能解决你的问题。现在我已经编辑了那段代码。 - ilango j
在Adapter类的构造函数中调用clearCache()方法。在调用getview()方法之前,缓存将被清除。 - ilango j

5
这对我来说更准确:

这对我来说更加准确:

private void initializeCache() {
    long size = 0;
    size += getDirSize(this.getCacheDir());
    size += getDirSize(this.getExternalCacheDir());
}

public long getDirSize(File dir){
    long size = 0;
    for (File file : dir.listFiles()) {
        if (file != null && file.isDirectory()) {
            size += getDirSize(file);
        } else if (file != null && file.isFile()) {
            size += file.length();
        }
    }
    return size;
}

3

Kotlin中,你可以使用:

context.cacheDir.walkBottomUp().fold(0L, { acc, file -> acc + file.length() })

或者将其定义为扩展函数

fun File.calculateSizeRecursively(): Long {
    return walkBottomUp().fold(0L, { acc, file -> acc + file.length() })
}


// usage
val size = context.cacheDir.calculateSizeRecursively()


1

...而要清除缓存,只需删除该目录并重新创建一个空目录。


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