我有一个带有SD卡的设备。现在我想检查一下设备已经挂载了外部SD卡,并且可以从公用DCIM文件夹读取文件。我知道我可以使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);,但是这个方法只返回文件,即主外部内存,而不是安装的SD卡(二级外部存储)。
我发现Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);返回一个索引1的元素,用于辅助外部存储,但是这个方法只为应用程序沙箱(Android/data/packagename)获取文件。那么,我的问题是如何为DCIM这样的公共目录获取辅助外部路径?
发布于 2015-08-19 06:52:21
我找到了解决方案,下面是代码片段:
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
}
}有关详细信息,请参阅此处:在Android设备上查找SDCard路径
发布于 2015-08-18 12:17:45
你试过这个吗?
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;
} }发布于 2015-08-18 12:55:25
要访问多个外部存储,可以使用api。
ContextCompat.getExternalCacheDirs(Context context);
ContextCompat.getExternalFilesDirs(Context context, String type);这将返回像/storage/sdcard1/Android/data/com.example.foo/这样的路径,然后可以用DCIM替换Android/data/com.example.foo/以获得所需的路径。
这种方法不可靠,因为路径Android/data/com.example.foo/将来会有所不同或改变,但值得一试。
您可以从官方android文档中看到更多信息。
https://stackoverflow.com/questions/32072095
复制相似问题