我花了几个小时尝试使用 Intent.ACTION_VIEW
从 Android 外部存储中打开图像。正如您可能已经发现的那样,我仍然无法做到这一点。
我在 Google 上进行了搜索,并尝试了很多方法来实现此目的,但没有一个成功。我能找到的都是 1 年前的问题。我尝试使用 FileProvider
,这就是我最终得到的结果:
File imagePath = new File(Environment.getExternalStorageDirectory(), "LyceeLamartine/cache");
File newFile = new File(imagePath, "calendrier.png");
Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "ml.toufic.lyceelamartine.fileprovider", newFile);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(contentUri, "image/*");
startActivity(intent);
上面的代码成功打开 Google Photos,但显示黑屏,路径似乎是:content://ml.toufic.lyceelamartine.fileprovider/name/calendrier.png
这似乎就像内部存储路径一样。
我想要访问的图像存储在:“/storage/emulated/0/LyceeLamartine/cache/calendrier.png”,并且我使用的是 Android O (8.0) 手机。
我仍然是 Java 的初学者,任何帮助将不胜感激!
最佳答案
the path seems to be: content://ml.toufic.lyceelamartine.fileprovider/name/calendrier.png and this seems like an internal storage path.
那不是一条路。这是一个 Uri
。它有一个方案(content
)。它指向您的 FileProvider
(ml.toufic.lyceelamartine.fileprovider
)。看起来不错 - 如果 Uri
存在问题,FileProvider
在您尝试创建它时会抛出异常。
The code above opens Google Photos successfully but it shows a black screen
您的Intent
有两个问题。
首先,不要使用通配符 MIME 类型。这是您的文件。 您知道 MIME 类型是什么。使用实际的 MIME 类型(在本例中为 image/png
)。
其次,在调用 startActivity()
之前,在 Intent
上调用 addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
作为设置的一部分。目前,没有任何应用程序无权使用您的内容。
关于java - 从外部存储打开图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722916/