如何获取当前Android应用程序占用的数据量?

时间:2016-08-02 19:35:40

标签: android xamarin.android package android-package-managers android-applicationinfo

我正在制作一个Android应用程序,并希望向用户显示我在手机上占用多少空间数据。

我目前正在获取数据库文件的大小,并打包应用程序文件,并将它们添加到一起,但它不在Android应用程序设置中显示的统计数据附近。

我想知道是否有办法让设置应用中显示数据: enter image description here

作为我目前的做法:

long dbsize = DAL.Repository.getDBSizeinKB(); // is 18 MB
ApplicationInfo appinfo = a.PackageManager.GetApplicationInfo(a.ApplicationInfo.PackageName, 0);
long appsize = new FileInfo(appinfo.SourceDir).Length / 1000; // 4MB
string spaceUsed = "";
long totalsize = dbsize + appsize;
spaceUsed = totalsize.ToString() + " kB";
if (totalsize >= 1000)
    spaceUsed = (totalsize / 1000).ToString() + " MB";
sizeView.Text = "Space used: " + spaceUsed; // 22MB

关闭。

1 个答案:

答案 0 :(得分:0)

尝试getting the root directory of your appgetting the size of all its directory tree recursively

PackageManager m = getPackageManager();
String s = getPackageName();
long size;
try {
    PackageInfo p = m.getPackageInfo(s, 0);
    s = p.applicationInfo.dataDir;
    File directory = new File(s);
    size = folderSize(directory);
} catch (PackageManager.NameNotFoundException e) {
    Log.w("yourtag", "Error Package name not found ", e);
}

folderSize():

public static long folderSize(File directory) {
    long length = 0;
    for (File file : directory.listFiles()) {
        if (file.isFile())
            length += file.length();
        else
            length += folderSize(file);
    }
    return length;
}