根据 uri 获取文件真实路径
前情提要:android 调用 系统相册 选择图片,并获取返回的uri,之后如何获取真实路径
1 2 3 4 5 6 | //判断安卓版本 if (resultCode == RESULT_OK && data != null ) { if (Build.VERSION.SDK_INT >= 19 ) handImage(data.getData()); else handImageLow(data); } |
//安卓小于4.4的处理方法
private void handImageLow(Intent data) {
Uri uri = data.getData();
String path = getImagePath(uri, null);
//展示图片
...获取真实路径 path
}
//content类型的uri获取图片路径的方法
private String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
//安卓版本大于4.4的处理方法
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void handImage(Uri uri) {
String path = null;
//根据不同的uri进行不同的解析
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
path = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
path = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
path = uri.getPath();
}
//展示图片
... 获取真实路径 path
}
时间过于久远,忘了原地址,所以放在了文章里
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具