我想通过打开由 startActivityForResult 选择的文件来获取文件路径,其 Intent 是 Intent.ACTION_GET_CONTENT 和 setType(*/*),但是当我选择打开形式的“Nexus 5X”项目时,返回的 uri 是“com. android.externalstorage.documents”,如何处理这种类型的uri。 有一些代码。
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.ACTION_DEVICE_STORAGE_OK, true);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("*/*");
startActivityForResult(intent, FILE_ADD_ACTION_REQUEST_CODE);
最佳答案
外部存储 URI 的形式如下:
content://com.android.externalstorage.documents/root%3Apath
其中 root
是存储介质的根目录,%3A
只是一个转义冒号,path
是相对于根(也转义)。
在具有模拟主存储的设备(即现代 Android 设备)上,主存储的根目录(即 /sdcard
)通常称为 primary
。在其他情况下,它似乎是媒体 ID(用连字符分隔的 4+4 个十六进制数字)。
您也可以尝试使用它(需要 API 21 才能获得全部功能):
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
// ExternalStorageProvider
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(':');
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
//getExternalMediaDirs() added in API 21
File[] external = context.getExternalMediaDirs();
if (external.length > 1) {
filePath = external[1].getAbsolutePath();
filePath = filePath.substring(0, filePath.indexOf("Android")) + split[1];
}
} else {
filePath = "/storage/" + type + "/" + split[1];
}
return filePath;
}
关于android - 如何通过权限为 "com.android.externalstorage.documents"的uri获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226029/