如何获取Camera文件的辅助外部目录的路径

问题描述 投票:1回答:3

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

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

android android-camera android-5.0-lollipop
3个回答
2
投票

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

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


0
投票

你试过这个吗?

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;
} }

0
投票

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

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

这将返回像/storage/sdcard1/Android/data/com.example.foo/这样的路径,然后你可以用Android/data/com.example.foo/替换DCIM来获得你想要的路径。

这种方法不可靠,因为路径Android/data/com.example.foo/将来会有所不同或改变,但值得尝试一下。

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

© www.soinside.com 2019 - 2024. All rights reserved.