Get available space of a connected USB Drive through USB OTG

46 views Asked by At

With StorageManager we can access removable flash drives connected via USB OTG to Android smartphones:

val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
storageManager.storageVolumes
    .forEach { volume ->
        Timber.d("uuid: ${volume.uuid}, storageUuid: ${volume.storageUuid}, path: ${volume.directory}, desc: ${volume.getDescription(context)}, state: ${volume.state}, isDir: ${volume.directory?.isDirectory}, isRemovable: ${volume.isRemovable}\nallocatedBytes: ${volume.storageUuid?.let { storageManager.getAllocatableBytes(it) }}")
    }

E.g.:

#1 built-in/internal primary storage:

uuid: null
storageUuid: 41217664-9172-527a-b3d5-edabb50a7d69
path: /storage/emulated/0
desc: Internal storage
state: mounted
isDir: true
isRemovable: false
allocatedBytes: 33695051776

#2 usb flash drive:

uuid: 8013-83C4
storageUuid: null
path: /mnt/media_rw/8013-83C4
desc: ESD-USB
state: mounted
isDir: false
isRemovable: true
allocatedBytes: null // because storageUuid is null here

We can't get free space from volumeEsdUsb.directory:

#1 with StatFs there will be an exception:

val stats = StatFs(volumeEsdUsb.directory.absolutePath)
val freeSpace = stats.availableBlocksLong * stats.blockSizeLong

java.lang.IllegalArgumentException: Invalid path: /mnt/media_rw/8013-83C4 at android.os.StatFs.doStat(StatFs.java:53) at android.os.StatFs.(StatFs.java:43)

#2 with volumeEsdUsb.directory.usableSpace it just returns 0

Is there any other solution to get free space on the flash drive Or Android doesn't have anything like this for USB flash drives from the box?

With Storage Access Framework there is no info at all about any volume storage, we can just get treeUri and use it with Document to work with files (create, edit, delete, move, copy)

0

There are 0 answers