Android Oreo DocumentsContract.getDocumentId(uri)返回路径而不是长路径
我正在尝试获取存储在Android文件系统中的文件的真实路径(我正在使用Android Oreo DocumentsContract.getDocumentId(uri)返回路径而不是长路径,android,file,path,filesystems,android-8.1-oreo,Android,File,Path,Filesystems,Android 8.1 Oreo,我正在尝试获取存储在Android文件系统中的文件的真实路径(我正在使用Android8.1在模拟器上进行测试) 这是我的密码: final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return ge
Android8.1
在模拟器上进行测试)
这是我的密码:
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
对于早期版本的Android 8.0
,变量id
包含一个long
值,因此下一行按预期工作
在安卓8上,变量id
包含如下路径raw:/storage/simulated/0/Download/my_file.pdf
,因此转换Long.valueOf(id))
会引发'java.lang.NumberFormatException'异常。
有什么想法吗?谢谢。通过执行以下操作解决了相同的问题
final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
return null;
}
}
在注释中找到了解决方案请在转换为long之前尝试添加此行:
str=str.replaceAll(“[^\\d.]”,“”)这样,如果字符串包含字母或符号,就不会有任何混淆。你的问题没有意义。如果您有类似于raw:/storage/emulated/0/Download/my_file.pdf
的内容,则路径是/storage/emulated/0/Download/my_file.pdf
。你在找什么?这对我来说很有意义。在Android 8
之前,变量id
包含一个Long
值,因此我可以使用有效路径准备contentUri
。从Android 8
,变量id
包含在Android
文件系统中找不到的无效路径。无法获取仅用于视频的图像的路径,我在获取“光标”时收到请求“标题查询不支持投影、选择或排序”我使用的是Android 9。这段代码捕获了异常,但之后没有任何有意义的操作。这是如何解决问题的?不幸的是,通过读取流来创建临时文件看起来更适用,看看这个