如何在android中获取内部SD卡存储和外部(删除)SD卡存储和系统存储以及可用内存状态?

时间:2014-07-12 10:49:24

标签: android storage android-sdcard removable

我是Android新手。我需要获取内部存储和外部存储以及系统存储的简单代码,以及如何获取可用内存(内部和外部)空间,总内存空间的详细信息。我的代码在下面,但它在" StatFs"中得到了错误。方法。提前谢谢。

    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);

}

1 个答案:

答案 0 :(得分: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):

您的代码假设上述路径为&#34; / mnt / extSdCard /&#34;。这不保证。在某些设备中 它是&#34; / mnt / external_sd /&#34;。还有其他名字..

您需要做的是从列出所有已安装的存储设备开始,并以某种方式(以编程方式,用户干预......)选择您的。这样做的方法如下:

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

}