我正在尝试获取存储在Android文件系统中的文件的真实路径(我正在使用Android 8.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
值,因此下一行按预期工作。
在Android 8
变量id
包含像这个raw:/storage/emulated/0/Download/my_file.pdf
的路径,所以铸造Long.valueOf(id))
投掷'java.lang.NumberFormatException' Exception.
有任何想法吗?谢谢。
如果通过以下方式解决了同样的问题。
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;
}
}