Android 26 returns 只有一条路 Context.getExternalFilesDirs()

Android 26 returns only one path Context.getExternalFilesDirs()

我正在使用 21、23、29、30 个 API 模拟器测试 Pixel,它们在使用时会 return 两条路径(第一个是外部内置 sdcard,第二个是外部可移动 sdcard) getExternalFilesDirs(null)方法:

但后来我尝试将 Pixel 与 26 API 一起使用,但我只有一条路径:

然后我找到了另一种获取所有存储路径的方法,这对我来说是 return 的新东西,通常它会以 /storage/ 开头,但现在它以 /mnt/media_rw/ 开头:

获取方法StorageManager:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
    val storageVolumes = storageManager.storageVolumes
    if (!storageVolumes.isNullOrEmpty()) {
        for (storageVolume in storageVolumes) {
            val volumePath = getVolumePath(storageVolume) ?: continue
            result.add(File(volumePath))
        }
    }
}


@RequiresApi(Build.VERSION_CODES.N)
private fun getVolumePath(storageVolume: StorageVolume): String? {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
        return storageVolume.directory?.absolutePath
    try {
        val storageVolumeClazz = StorageVolume::class.java
        val getPath = storageVolumeClazz.getMethod("getPath")
        return getPath.invoke(storageVolume) as String
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

你可以看到这个方法甚至使用反射 API < R (30)

所以我得到了 Pixel 26 API 的路径 /mnt/media_rw/1D13-0D17。我不明白为什么与其他 API 不同。

但是这个路径还不能访问,我无法读取它。然后我尝试使用来自 Google Play 的一些流行的文件 Browser/Explorer 应用程序,我发现它们需要一些权限才能访问此类外部可移动存储:

我以前从未见过这样的事情。他们是怎么做到的,为什么它会存在?

我有21、23、29、30 API 和 none 的真实设备需要使用这种方法来访问外部可移动存储,我可以使用 getExternalFilesDirs(null) .同样适用于具有相同 API

的 Pixel 模拟器

那么 /mnt/media_rw/* 从何而来以及如何请求从我的应用程序访问它的权限以及如果我不需要其他 API 则为什么我什至需要授予此权限去做吗?

我在官方 Android 文档中找不到有关它的任何信息

So I got this path /mnt/media_rw/1D13-0D17 for Pixel 26 API. I don't understand why there is difference from other APIs. But this path is not accessible yet, I can't read it. Then I tried to use some popular Files Browser/Explorer apps from Google Play and I found out that they request some permission to get access to such external removable storage:

我发现这样的路径也不可读且无法列出。

但为什么其他应用可以?我认为他们不能太使用文件 class。 他们将使用存储访问框架。

例如SDK 27是AndroidO.

对于 Android N、O 和 P,您的应用可以创建访问意图:

volume.createAccessIntent()

请尝试。