How to get cache size in Android

前端 未结 3 2000
长情又很酷
长情又很酷 2021-01-07 02:35

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 loade

相关标签:
3条回答
  • 2021-01-07 02:42

    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.

    0 讨论(0)
  • 2021-01-07 02:52

    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;
    }
    
    0 讨论(0)
  • 2021-01-07 02:58

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

    0 讨论(0)
提交回复
热议问题