有可能获得总存储容量吗?

时间:2013-01-25 23:13:35

标签: android storage sd-card

我知道如何获得内存和外部存储空闲容量。

但我想知道内存的最大容量和外部存储的最大容量,但我在谷歌上找不到任何关于它的信息

有可能实现吗?

感谢

4 个答案:

答案 0 :(得分:4)

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;

Source

另外,请将其用于内部尺寸。

StatFs stat = new StatFs(Environment.getDataDirectory().getPath());

答案 1 :(得分:4)

API 18中引入了一些新方法。这是我用来获取总存储量的代码(内部+外部)。

private static final long KILOBYTE = 1024;

StatFs internalStatFs = new StatFs( Environment.getRootDirectory().getAbsolutePath() );
long internalTotal;
long internalFree;

StatFs externalStatFs = new StatFs( Environment.getExternalStorageDirectory().getAbsolutePath() );
long externalTotal;
long externalFree;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
    internalTotal = ( internalStatFs.getBlockCountLong() * internalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
    internalFree = ( internalStatFs.getAvailableBlocksLong() * internalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
    externalTotal = ( externalStatFs.getBlockCountLong() * externalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
    externalFree = ( externalStatFs.getAvailableBlocksLong() * externalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
}
else {
    internalTotal = ( (long) internalStatFs.getBlockCount() * (long) internalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
    internalFree = ( (long) internalStatFs.getAvailableBlocks() * (long) internalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
    externalTotal = ( (long) externalStatFs.getBlockCount() * (long) externalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
    externalFree = ( (long) externalStatFs.getAvailableBlocks() * (long) externalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
}

long total = internalTotal + externalTotal;
long free = internalFree + externalFree;
long used = total - free;

答案 2 :(得分:0)

此方法不适用于所有手机,大多数手机都会返回用户可用的内存总量,减少系统内存。您可以尝试使用' df -h' linux命令在使用NDK的c ++方法中,但有些手机只能使用系统(su)命令。所以它的长短是你无法做到的。

答案 3 :(得分:0)

StatFs - 检索有关文件系统空间的整体信息。这是Unix statvfs()的包装器。

从API级别18我们使用

long getTotalBytes - The total number of bytes supported by the file system. 

对于较旧的API使用

int getBlockCount ()
int getBlockSize ()

StatFs stat = new StatFs(**path**);
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();

作为路径您使用Environment.getExternalStorageDirectory(),请查看此值。在具有多个共享/外部存储目录的设备中,此目录表示用户将与之交互的主存储。

您需要使用路径的字符串值,如下所示: " / MNT / external_sd /" " / MNT / extSdCard /"

您可以检索所有 / mnt / 设备的列表,并使用其中一个值。

File allMounted = new File("/mnt/");
if(allMounted.isDirectory()){ 
String[] dirs = allMounted.list();...}

或类似

var myfile=new Java.IO.File("storage/");
var listOfStorages=myfile.ListFiles();

String[] externals = System.getenv("SECONDARY_STORAGE").split(":");