2

I'm new to Android. I need the simple code of getting the Internal storage and external storage and System storage and how to get the Details of available memory(internal and external) space, total memory space. My code is below but its getting error in "StatFs" method. Thanks in advance.

    long total, aval,total1, aval1,total2, aval2;
    int kb = 1024;

    StatFs fs = new StatFs(Environment.
                            getExternalStorageDirectory().getPath());

    total = fs.getBlockCount() * (fs.getBlockSize() / kb);
    aval = fs.getAvailableBlocks() * (fs.getBlockSize() / kb);
    //Here Iam Getting error StatFs method not loading
    StatFs fs1 = new StatFs(Environment.
    getRootDirectory()+"/storage/extSdCard/");


 total1 = fs1.getBlockCount() * (fs1.getBlockSize() / kb);
 aval1 = fs1.getAvailableBlocks() * (fs1.getBlockSize() / kb);

    pb1.setMax((int)total);
    pb1.setProgress((int)aval);
    pb2.setMax((int)total1);
    pb2.setProgress((int)aval1);

}
4

1 回答 1

2

访问 SDCARD 服务时始终首先检查 SDCARD 当前是否已安装。你不能假设它是:

String state = Environment.getExternalStorageState();

if (state.equals(android.os.Environment.MEDIA_MOUNTED)) {
       // is mounted, can continue and check size

        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long AvailableBytes = (long)stat.getBlockSize() *(long)stat.getBlockCount();
        long AvailableInMegas = AvailableBytes / 1048576; // <------------------
}


现在,要获得可用的内部存储:

File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
long availableInternalInBytes = formatSize(availableBlocks * blockSize);

注意:以上内容将为所有人返回可用的存储空间,而不仅仅是您的应用程序!


获取内存使用情况:

final Runtime runtime = Runtime.getRuntime();
final long totalMem = runtime.totalMemory(); // <--------- total for YOUR JVM!
final long freeMem = runtime.freeMemory();  // <--------- free in YOUR JVM!
final long usedMem = totalMem - freeMem; // <--------- used in YOUR JVM!
final long maxMem = runtime.maxMemory()  // <--------- the max amount of mem that YOUR JVM may attempt to use

所有值都以字节为单位。


最后 - 询问外部存储器(不是 SDCARD):

您的代码假定上面的路径是“/mnt/extSdCard/”。这不能保证。在某些设备中,它是“/mnt/external_sd/”。而且还可以有别的名字。。

您需要做的是首先列出所有已安装的存储设备,然后以某种方式(以编程方式,用户干预......)选择您的一个。方法如下:

File mountedRoot = new File("/mnt/");
if(mountedRoot.isDirectory()) {
    String[] allMountedFolders = storageDir.list();
    if (allMountedFolders != null) {
         for (String f: allMountedFolders) {
               // iterate over all mounted devices <-----------------------
         }
    }

}
于 2014-07-12T10:55:16.450 回答