当使用如下代码调用安卓的自带文件选择
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(\"video/*\");
intent.addCategory(intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, \"请选择视频文件\"),RequestCode);
如果在选择时使用的文件选择器为 下载内容 将会导致使用返回的URI获取绝对路径时出现类似如下错误:
java.lang.IllegalArgumentException
Unknown URI: content://downloads/public_downloads/1944
java.lang.RuntimeException:Failure delivering result ResultInfo{who=null, request=1000, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/1944 flg=0x1 }} to activity {com.equationl.videoshotpro/com.equationl.videoshotpro.MainActivity}: java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/1944
修复前使用的转换URI的部分代码如下:
public String getImageAbsolutePath(Activity context, Uri imageUri) {
.............
.............
else if (isDownloadsDocument(imageUri)) {
String id = DocumentsContract.getDocumentId(imageUri);
if (id.startsWith(\"raw:\")) {
final String path = id.replaceFirst(\"raw:\", \"\");
return path;
}
Uri contentUri = ContentUris.withAppendedId(Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
.........
.........
}
通过查找资料,发现原来只需要将上述代码更改为:
public String getImageAbsolutePath(Activity context, Uri imageUri) {
.............
.............
else if (isDownloadsDocument(imageUri)) {
String id = DocumentsContract.getDocumentId(imageUri);
if (id.startsWith(\"raw:\")) {
final String path = id.replaceFirst(\"raw:\", \"\");
return path;
}
Uri contentUri = imageUri;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
contentUri = ContentUris.withAppendedId(
Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id));
}
.........
.........
}
即可解决上述问题。
至于错误原因从上述代码中不难看出,在高于安卓O(8.0)版本时将URI设为
contentUri = ContentUris.withAppendedId(
Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id));
会导致 Unknown URI 的问题,所以只需要判断一下当前的安卓版本,如果大于 O 则直接使用文件选择器返回的URI即可。
以上为我所使用的解决方案,对于不同的项目可能有不同的解决方案,可以看一下下面这项目里面的 issue
参考案例
继续阅读与本文标签相同的文章
-
POLARDB MySQL 8.0 正式上线商用
2026-05-18栏目: 教程
-
MySQL 推出 90核 CPU 720GB 内存 独占物理机规格
2026-05-18栏目: 教程
-
基于 RocketMQ 的同城双活架构在美菜网的挑战与实践
2026-05-18栏目: 教程
-
账户系统如何应对高并发、热点账户等问题
2026-05-18栏目: 教程
-
阿里雷卷:Reactive 基金会的成立将对开发方式带来哪些影响?
2026-05-18栏目: 教程
