如何获取缓存目录的确切大小:android [英] 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.
我的方法:
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();
}
}
结果:如果目录为null,则返回0(作为条件).但是如果目录存在,则总是返回4 Kb.我按照以下过程签出了我的应用程序的缓存:
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
但是我在那里找到了它的0B.
But I found its 0B there.
为什么有人可以解释它的发生?以及如何获取缓存的确切大小?
Why its happening can someone explain? and How do I get exact size of cache?
推荐答案
目录的调用长度并不总是返回正确的大小.您可以尝试遍历文件列表并累加所有文件大小以获得总目录大小.
Calling length on a directory doesn't always return the correct size. You could try to iterate over the file list and add up all file sizes to get the total directory size.
赞:
long size = 0;
File[] files = cacheDirectory.listFiles();
for (File f:files) {
size = size+f.length();
}
这篇关于如何获取缓存目录的确切大小:android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!