带有 Intent 和 FileProvider 的 Android 打开资产图像文件显示大小 0
我将所有文件放在 assets 文件夹中,并使用以下功能打开它们:
fun Fragment.openAssetsFile(fileName: String) {
val file = getAssetsFile(fileName)
val fileUri = FileProvider.getUriForFile(requireContext(), "${requireContext().packageName}.provider", file)
val intent = Intent(Intent.ACTION_VIEW).apply {
type = "application/${file.extension}" //<- doesn't work for image (jpg, png)
data = fileUri
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(intent)
}
fun Fragment.getAssetsFile(fileName: String): File {
val file = File(requireContext().filesDir, fileName)
if (!file.exists()) {
file.outputStream().use { outputStream ->
requireContext().assets.open(fileName).use { inputStream ->
inputStream.copyTo(outputStream)
}
}
}
return file
}
与 Word、Excel、PPT、PDF、Mp4、Mp3 完美配合,但对于 >JPG、PNG 它显示 0 大小,如下所示:
(已尝试设置 mime 类型 image/*
但没有帮助。)
更新:在三星 Tab S5e 平板电脑、三星 S22 Ultra、华为 P50 Pro 和三星 Note 9 上测试,仅 Note 9 存在问题。
I place all the files in assets folder and use following functions to open them:
fun Fragment.openAssetsFile(fileName: String) {
val file = getAssetsFile(fileName)
val fileUri = FileProvider.getUriForFile(requireContext(), "${requireContext().packageName}.provider", file)
val intent = Intent(Intent.ACTION_VIEW).apply {
type = "application/${file.extension}" //<- doesn't work for image (jpg, png)
data = fileUri
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(intent)
}
fun Fragment.getAssetsFile(fileName: String): File {
val file = File(requireContext().filesDir, fileName)
if (!file.exists()) {
file.outputStream().use { outputStream ->
requireContext().assets.open(fileName).use { inputStream ->
inputStream.copyTo(outputStream)
}
}
}
return file
}
Working perfectly fine with Word, Excel, PPT, PDF, Mp4, Mp3, but for JPG, PNG it shows 0 size like this:
(Had tried setting the mime type image/*
but no help.)
Update: Tested on Samsung Tab S5e tablet, Samsung S22 Ultra, Huawei P50 Pro and Samsung Note 9, only the Note 9 has the issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我尝试将
.png
和.jpeg
复制到资产文件夹中,我可以使用上述功能访问和查看这两个文件。我刚刚传递了我的文件名以及扩展名,如下所示:
或者
确保您已在 Android Manifest 文件中添加文件提供程序:
在
res/xml
下添加此provider_paths.xml
目录然后它应该可以工作。
`
I tried by copying a
.png
and.jpeg
into the assets folder and I can able to access and view both files using the above functions.I just passed my file name along with extensions like below:
OR
Make sure you have added the file provider in the Android Manifest file:
add this
provider_paths.xml
underres/xml
directoryThen it should work.
`