开发者

How to get cache size in Android

I'm using fedor's lazy loading list implementation in my test application where I can clear the cache with a single button click. How can I get the cache size of the loaded images in the listview and clear the cache programmatically?

Here is the code for saving the cached images:

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.getE开发者_如何学运维xternalStorageDirectory(),"LazyList");
    else
        cacheDir = context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

EDIT:

So basically I added this piece of code in clearCache(), method, but I still cannot see the images start loading again when I'm scrolling.

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


To find the size of the cache directory use the codebelow.

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

This will return the number of bytes.


This has been more accurate to me:

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


In Kotlin, you can use:

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

or define it as an extension function

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


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


...and to clear cache, just delete the directory and recreate an empty one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜