Android 日常开发(48)android.os.FileUriExposedException最佳解决办法

本文深入探讨了Android中遇到的android.os.FileUriExposedException异常,并提供了通过使用Android的FileProvider类来解决该问题的方法。针对Android 7.0及以上版本的安全要求,建议开发者使用content:// Uri替代file:// Uri,以确保文件访问权限的安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

我之前在weex的问题合集里面讲过一次这种异常的处理办法不过当时时通过关闭android严苛模式的视角处理的。今天我们来深入sdk,看看这个问题的最佳解决方式

1.我们通过android developer官网搜索android.os.FileUriExposedException这个异常

The exception that is thrown when an application exposes a file:// Uri
to another app.

This exposure is discouraged since the receiving app may not have
access to the shared path. For example, the receiving app may not have
requested the Manifest.permission.READ_EXTERNAL_STORAGE runtime
permission, or the platform may be sharing the Uri across user profile
boundaries.

Instead, apps should use content:// Uris so the platform can extend
temporary permission for the receiving app to access the resource.

This is only thrown for applications targeting Build.VERSION_CODES#N
or higher. Applications targeting earlier SDK versions are allowed to
share file:// Uri, but it’s strongly discouraged.

Android 7.0在文件安全方面提出了更多要求,需要开发者做成额外的配置来明确需求。

2.解决方法
了解FileProvider类的使用

快速解决问题如下:
1.在清单文件里面配置


        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xxx.fileprovider"
            android:exported="false"</
安卓 WebView跳转页面时可能会出现android.os.FileUriExposedException异常。这个异常是因为Android的安全机制限制了应用程序直接暴露本地文件的URI给其他应用程序。当我们在WebView中点击一个链接,如果该链接指向的是一个本地文件的URI,就会抛出这个异常。 解决这个问题的方法有两种: 1. 使用FileProvider:可以通过使用FileProvider来解决这个问题。FileProvider是一个特殊的ContentProvider,它可以控制共享文件的权限。我们需要在AndroidManifest.xml文件中注册FileProvider,并为要共享的文件配置相应的访问权限。然后,可以使用FileProvider的getUriForFile()方法将文件URI转换为共享URI,然后通过Intent将共享URI传递给WebView。这样可以绕过安全限制,使WebView能够顺利跳转到文件页面。 2.AndroidManifest.xml中添加文件权限:在应用程序的AndroidManifest.xml文件中添加文件访问权限可以解决此异常。我们可以使用如下代码在<application>标签内添加文件权限: <application ... android:requestLegacyExternalStorage="true"> ... </application> 这样可以设置应用程序使用旧版的外部存储沙盒,从而绕过安全限制,解决异常问题。 总结来说,当安卓WebView跳转页面时出现android.os.FileUriExposedException异常,可以使用FileProvider或者在AndroidManifest.xml中添加文件权限的方式解决。这样可以保证WebView可以顺利跳转到文件页面,而不会触发安全限制导致的异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值