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

NEEDED: I'm just trying to get the size of the occupied cache for each application that is installed on 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 the directory is null, it returns 0 (as a condition). But if the directory exists, its return 4 Kb always. I checked my application cache by doing this process:

Settings: → Programs: → ApplicationName

But I found 0B there.

Why can someone explain his case? and how to get the exact cache size?

+6
source share
3 answers

Directory call length does not always return the correct size. You can try iterating over the list of files and merging all file sizes to get the total size of the directory.

Like this:

 long size = 0; File[] files = cacheDirectory.listFiles(); for (File f:files) { size = size+f.length(); } 
+9
source

This was more accurate for 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]; } 

The initial position of the string formatting code in bytes

+5
source

you will get cachesize from this function

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

Source: https://habr.com/ru/post/943590/


All Articles