首页 > 解决方案 > Android - 在 android 库中显示图像

问题描述

我需要打开一张照片,我有红色可以使用默认的 android 画廊,但我无法让它工作。
我查看了几个论坛,最后我得到了这个代码,但它打开了一个黑色的图像。
我正在使用 api 最低 16 和目标 29,在 api 29 上进行测试。
有人可以帮助我吗?
谢谢。

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("content://"+"/storage/emulated/0/photo.jpg"), "image/*");
startActivity(intent);

已经尝试过 Uri.fromFile() 但不起作用。

标签: androidandroid-intent

解决方案


您可以改用 Uri.fromFile()

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/storage/emulated/0/photo.jpg")), "image/*");
startActivity(intent);

但是您会收到 FileURIExposed 错误,因此您需要在 oncreate() 中添加此代码

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build);

注意:不要使用硬编码路径使用环境

不是最好的答案,但效果很好


推荐阅读