如果您的内容Uri带有content://...,则可以使用此方法获取Android 19或更高版本上的文件夹或文件的绝对路径。
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = .SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && (context, uri)) {
(\"getPath() uri: \" + ());
(\"getPath() uri authority: \" + ());
(\"getPath() uri path: \" + ());
// ExternalStorageProvider
if (\"\".equals(())) {
final String docId = (uri);
final String[] split = (\":\");
final String type = split[0];
(\"getPath() docId: \" + docId + \", split: \" + + \", type: \" + type);
// This is for checking Main Memory
if (\"primary\".equalsIgnoreCase(type)) {
if ( > 1) {
return () + \"/\" + split[1] + \"/\";
} else {
return () + \"/\";
}
// This is for checking SD Card
} else {
return \"storage\" + \"/\" + (\":\", \"/\");
}
}
}
return null;
}
您可以检查Uri的每个部分是否正在使用println。以下列出了我的SD卡和设备主内存的返回值。您可以访问和删除文件是否在内存中,但是我无法使用此方法从SD卡中删除文件,只能读取或打开
d使用此绝对路径的图像。如果您找到使用此方法删除的解决方案,请分享。
SD卡
getPath() uri: content:///tree/612E-B7BF%3A/document/612E-B7BF%3A
getPath() uri authority:
getPath() uri path: /tree/612E-B7BF:/document/612E-B7BF:
getPath() docId: 612E-B7BF:, split: 1, type: 612E-B7BF
主要记忆
getPath() uri: content:///tree/primary%3A/document/primary%3A
getPath() uri authority:
getPath() uri path: /tree/primary:/document/primary:
getPath() docId: primary:, split: 1, type: primary
如果您希望在获取路径后使用file:///获得Uri
DocumentFile documentFile = (new File(path));
() // will return a Uri with file Uri