Skip to content

Commit b591ec8

Browse files
author
tanpengcheng
committed
[feat] Add SD card utils.
1 parent fe9baba commit b591ec8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.tans.tfiletransporter.file
2+
3+
import android.content.Context
4+
import android.os.Build
5+
import android.os.storage.StorageManager
6+
import android.os.storage.StorageVolume
7+
8+
/**
9+
* returns a list of all available sd cards paths, or null if not found.
10+
*
11+
* @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
12+
*/
13+
fun getSdCardPaths(context: Context, includePrimaryExternalStorage: Boolean): List<String> {
14+
val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
15+
val storageVolumes = storageManager.storageVolumes
16+
if (storageVolumes.isNotEmpty()) {
17+
val primaryVolume = storageManager.primaryStorageVolume
18+
val result = ArrayList<String>(storageVolumes.size)
19+
for (storageVolume in storageVolumes) {
20+
val volumePath = getVolumePath(storageVolume) ?: continue
21+
if (storageVolume.uuid == primaryVolume.uuid || storageVolume.isPrimary) {
22+
if (includePrimaryExternalStorage)
23+
result.add(volumePath)
24+
continue
25+
}
26+
result.add(volumePath)
27+
}
28+
return result
29+
} else {
30+
return emptyList()
31+
}
32+
}
33+
34+
private fun getVolumePath(storageVolume: StorageVolume): String? {
35+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
36+
return storageVolume.directory?.absolutePath
37+
try {
38+
val storageVolumeClazz = StorageVolume::class.java
39+
val getPath = storageVolumeClazz.getMethod("getPath")
40+
return getPath.invoke(storageVolume) as String
41+
} catch (e: Exception) {
42+
e.printStackTrace()
43+
}
44+
return null
45+
}

0 commit comments

Comments
 (0)