Skip to content

Instantly share code, notes, and snippets.

@gavingt
Last active April 5, 2022 06:25
Show Gist options
  • Save gavingt/2eb239d5df4e56290c1c65f25b8db8bf to your computer and use it in GitHub Desktop.
Save gavingt/2eb239d5df4e56290c1c65f25b8db8bf to your computer and use it in GitHub Desktop.
// Returns true if the given StorageVolume is an SD card.
// This reads the proc/mounts file, which contains mount info for all drives on device.
// A USB drive will show on a line like: /dev/block/vold/public:8,1 on /mnt/media_rw/68C9-D020 type vfat (rw,dirsync,nosuid,nodev,noexec,noatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,codepage=437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro)
// An SD card will show on a line like: /dev/block/vold/public:179,65 on /mnt/media_rw/084E-056D type vfat (rw,dirsync,nosuid,nodev,noexec,noatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,codepage=437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro)
// The /dev/block/vold/public:8 indicates a USB drive at 68C9-D020, while /dev/block/vold/public:179 indicates an SD card at 084E-056D.
@RequiresApi(ANDROID_7_SDK_24)
fun isStorageVolumeAnSdCard(storageVolume: StorageVolume): Boolean {
if (storageVolume.uuid == null) return false
var bufferedReader: BufferedReader? = null
var inputStream: InputStream? = null
var inputStreamReader: InputStreamReader? = null
var sdCardFound = false
try {
val runtime = Runtime.getRuntime()
val process = runtime.exec("mount")
inputStream = process.inputStream
inputStreamReader = InputStreamReader(inputStream)
bufferedReader = BufferedReader(inputStreamReader)
bufferedReader.forEachLine { line ->
if (line.contains(storageVolume.uuid!!, true) && line.contains("fat")
&& line.contains("media_rw") && line.contains("/dev/block/vold/public:179")
) {
sdCardFound = true
return@forEachLine
}
}
} catch (ignored: Exception) {
} finally {
try {
bufferedReader?.close()
inputStream?.close()
inputStreamReader?.close()
} catch (ignored: Exception) {
}
}
return sdCardFound
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment