Oreo DocumentsContract.getDocumentId(uri)返回路径而不是Long

问题描述 投票:9回答:1

我正在尝试获取存储在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.

有任何想法吗?谢谢。

android file path filesystems android-8.1-oreo
1个回答
13
投票

如果通过以下方式解决了同样的问题。

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;
            }
      }

解决方案在评论https://github.com/Yalantis/uCrop/issues/318中找到

© www.soinside.com 2019 - 2024. All rights reserved.