Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

caching - How to get the exact size of cache directory : android

NEED: I simply trying to get occupied cache size of each application which is installed in my phone.

MY APPROACH:

PackageManager packageManager = getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) 
{
    try 
    {
        Context mContext = createPackageContext(packageInfo.packageName, CONTEXT_IGNORE_SECURITY);
        File cacheDirectory = mContext.getCacheDir();
        if(cacheDirectory==null)
        {
            cacheArrayList.add("0");
        }
        else
        {
            cacheArrayList.add(String.valueOf(cacheDirectory.length()/1024));
        }
    }
    catch (NameNotFoundException e)
    {
        e.printStackTrace();
    }
}

RESULT: If directory is null it returning 0 (as condition). But if directory existing its returning 4 Kb always. I checked out cache of my apps by following the process:

Settings:->Apps:->ApplicationName

But I found its 0B there.

Why its happening can someone explain? and How do I get exact size of cache?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This has been more accurate to me:

private void initializeCache() {
    long size = 0;
    size += getDirSize(this.getCacheDir());
    size += getDirSize(this.getExternalCacheDir());
    ((TextView) findViewById(R.id.yourTextView)).setText(readableFileSize(size));
}

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

public static String readableFileSize(long size) {
    if (size <= 0) return "0 Bytes";
    final String[] units = new String[]{"Bytes", "kB", "MB", "GB", "TB"};
    int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

Original post of the string to bytes formatting code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...