Android get free size of internal/external memory

前端 未结 13 1232
眼角桃花
眼角桃花 2020-11-22 15:20

I want to get the size of free memory on internal/external storage of my device programmatically. I\'m using this piece of code :

StatFs stat = new StatFs(En         


        
13条回答
  •  青春惊慌失措
    2020-11-22 15:43

    To get all available storage folders (including SD cards), you first get the storage files:

    File internalStorageFile=getFilesDir();
    File[] externalStorageFiles=ContextCompat.getExternalFilesDirs(this,null);
    

    Then you can get the available size of each of those.

    There are 3 ways to do it:

    API 8 and below:

    StatFs stat=new StatFs(file.getPath());
    long availableSizeInBytes=stat.getBlockSize()*stat.getAvailableBlocks();
    

    API 9 and above:

    long availableSizeInBytes=file.getFreeSpace();
    

    API 18 and above (not needed if previous one is ok) :

    long availableSizeInBytes=new StatFs(file.getPath()).getAvailableBytes(); 
    

    To get a nice formatted string of what you got now, you can use:

    String formattedResult=android.text.format.Formatter.formatShortFileSize(this,availableSizeInBytes);
    

    or you can use this in case you wish to see exact bytes number but nicely:

    NumberFormat.getInstance().format(availableSizeInBytes);
    

    Do note that I think the internal storage could be the same as the first external storage, since the first one is the emulated one.


    EDIT: Using StorageVolume on Android Q and above, I think it's possible to get the free space of each, using something like:

        val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
        val storageVolumes = storageManager.storageVolumes
        AsyncTask.execute {
            for (storageVolume in storageVolumes) {
                val uuid: UUID = storageVolume.uuid?.let { UUID.fromString(it) } ?: StorageManager.UUID_DEFAULT
                val allocatableBytes = storageManager.getAllocatableBytes(uuid)
                Log.d("AppLog", "allocatableBytes:${android.text.format.Formatter.formatShortFileSize(this,allocatableBytes)}")
            }
        }
    

    I'm not sure if this is correct, and I can't find a way to get the total size of each, so I wrote about it here, and asked about it here.

提交回复
热议问题