Skip to content

Instantly share code, notes, and snippets.

@gavingt
Last active November 21, 2021 22:36
Show Gist options
  • Save gavingt/c43bfb876ad78571b72e8bc6fd8ffb82 to your computer and use it in GitHub Desktop.
Save gavingt/c43bfb876ad78571b72e8bc6fd8ffb82 to your computer and use it in GitHub Desktop.
// Detects if user granted permissions to USB drive root, rather than accidentally granting it to some other folder.
private fun driveHasRootPermission(uri: Uri): Boolean {
val documentFileFromUri = DocumentFile.fromTreeUri(appContext, uri)
val nameFromUri = documentFileFromUri?.name ?: ""
if (Build.VERSION.SDK_INT >= ANDROID_11_SDK_30) {
val recentExternalVolumeNames = getRecentExternalVolumeNames(appContext).map { it.lowercase() }
// Checks whether the user-selected Uri points to a writable location and its name matches that of a recently used external volume.
if (documentFileFromUri?.canWrite() == true && recentExternalVolumeNames.contains(nameFromUri.lowercase())) return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment