From cc1ca9f9500800908621f8e4584f39e1a611a998 Mon Sep 17 00:00:00 2001 From: Thibault Deckers Date: Tue, 8 Mar 2022 18:46:26 +0900 Subject: [PATCH] #167 improved volume fetch for Android 11+ --- .../thibault/aves/utils/StorageUtils.kt | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt index a420fb1f3..03d158403 100644 --- a/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt @@ -115,6 +115,15 @@ object StorageUtils { } private fun findPrimaryVolumePath(context: Context): String? { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + val path = sm?.primaryStorageVolume?.directory?.path + if (path != null) { + return ensureTrailingSeparator(path) + } + } + + // fallback try { // we want: // /storage/emulated/0/ @@ -130,9 +139,16 @@ object StorageUtils { } private fun findVolumePaths(context: Context): Array { - // Final set of paths - val paths = HashSet() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + val paths = sm?.storageVolumes?.mapNotNull { it.directory?.path } + if (paths != null) { + return paths.map(::ensureTrailingSeparator).toTypedArray() + } + } + // fallback + val paths = HashSet() try { // Primary emulated SD-CARD val rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET") ?: "" @@ -143,7 +159,8 @@ object StorageUtils { var validFiles: Boolean do { // `getExternalFilesDirs` sometimes include `null` when called right after getting read access - // (e.g. on API 30 emulator) so we retry until the file system is ready + // (e.g. on API 30 emulator) so we retry until the file system is ready. + // TODO TLAD It can also include `null` when there is a faulty SD card. val externalFilesDirs = context.getExternalFilesDirs(null) validFiles = !externalFilesDirs.contains(null) if (validFiles) {