如何获取相机文件的二级外部目录路径

How get path to secondary external directory for Camera files

我有一个带有 SD 卡的设备。现在我想检查设备是否安装了外部 SD 卡并且可以从 public DCIM 文件夹中读取文件。我知道我可以使用 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);,但这种方法 returns 仅文件,即在主外部存储器上,而不是在安装的 SD 卡(辅助外部存储器)上。

我发现 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); returns 一个索引为 1 的元素,用于辅助外部存储,但此方法仅获取应用程序沙箱 (Android/data/packagename) 的文件。所以我的问题是如何获取 public 目录(如 DCIM)的辅助外部路径的路径?

你试过吗?

private boolean canWriteToFlash() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    return true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // Read only isn't good enough
    return false;
} else {
    return false;
} }

要访问多个外部存储,您可以使用 api

 ContextCompat.getExternalCacheDirs(Context context);
 ContextCompat.getExternalFilesDirs(Context context, String type);

这将return一个类似于/storage/sdcard1/Android/data/com.example.foo/的路径,然后您可以将Android/data/com.example.foo/替换为DCIM以获得您想要的路径。

这个方法不靠谱,因为以后的路径Android/data/com.example.foo/会不一样或者改变,但值得一试。

您可以从 official android documents 查看更多信息。

我找到了解决方案,这里是代码片段:

String strSDCardPath = System.getenv("SECONDARY_STORAGE");

if ((strSDCardPath == null) || (strSDCardPath.length() == 0)) {
    strSDCardPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
}

//If may get a full path that is not the right one, even if we don't have the SD Card there. 
//We just need the "/mnt/extSdCard/" i.e and check if it's writable
if(strSDCardPath != null) {
    if (strSDCardPath.contains(":")) {
        strSDCardPath = strSDCardPath.substring(0,strSDCardPath.indexOf(":"));
    }
    File externalFilePath = new File(strSDCardPath);

    if (externalFilePath.exists() && externalFilePath.canWrite()) {
        //do what you need here
    } 
}

有关详细信息,请阅读此处:Finding the SDCard Path on Android devices