Android 7.0行为变更 FileUriExposedException解决方法
作者:lqh 时间:2023-07-28 01:38:29
Android 7.0行为变更 FileUriExposedException解决方法
当我们开发关于【在应用间共享文件】相关功能的时候,在Android 7.0上经常会报出此运行时异常,那么Android 7.0以下没问题的代码,为什么跑到Android 7.0+的设备上运行就出问题了呢?,这主要来自于Android 7.0的一项【行为变更】!
对于面向 Android 7.0 的应用,Android 框架执行的 StrictMode API 政策禁止在您的应用外部公开 file:// URI。如果一项包含文件 URI 的 intent 离开您的应用,则应用出现故障,并出现 FileUriExposedException 异常。如图:
要在应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider 类。
FileProvider 类的用法:
第一步:为您的应用定义一个FileProvider清单条目,这个条目可以声明一个xml文件,这个xml文件用来指定应用程序可以共享的目录。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
在这段代码中, android:authorities 属性应该是唯一的,推荐使用【应用包名+fileprovider】,推荐这样写
android:authorities=”${applicationId}.file_provider”,可以自动找到应用包名。
meta-data标签指定了一个路径,这个路径使用resource指定的xml文件来指明是那个路径:
xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="bga_upgrade_apk" path="upgrade_apk" />
</paths>
Uri的获取方式也要根据当前Android系统版本区分对待:
File dir = getExternalFilesDir("user_icon");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
icon_path = FileProvider.getUriForFile(getApplicationContext(),
"com.mqt.android_headicon_cut.file_provider", new File(dir, TEMP_FILE_NAME));
} else {
icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
}
这样问题就解决了。贴上一个安装apk适配7.0的例子:https://www.jb51.net/article/113307.htm
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:http://blog.csdn.net/qq_27512671/article/details/71439571
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java流程控制break和continue
![](https://img.aspxhome.com/file/2023/6/85536_0s.png)
Idea jdk版本问题解决方案
![](https://img.aspxhome.com/file/2023/9/108199_0s.png)
springboot实现文件上传步骤解析
mybatis-plus 如何使用雪花算法ID生成策略
![](https://img.aspxhome.com/file/2023/7/106087_0s.jpg)
Java SE 面向对象编程的3个常用接口
![](https://img.aspxhome.com/file/2023/5/95845_0s.png)
深入探讨linux下进程的最大线程数、进程最大数、进程打开的文件数
Android如何通过手机自动获取短信验证码
![](https://img.aspxhome.com/file/2023/6/106816_0s.png)
Java8如何从一个Stream中过滤null值
spring mvc实现文件上传与下载功能
在Spring中自动装配Bean的属性
android中实现指针滑动的动态效果方法
![](https://img.aspxhome.com/file/2023/6/139226_0s.jpg)
Android如何创建可拖动的图片控件
![](https://img.aspxhome.com/file/2023/6/138486_0s.jpg)
Mybatis关于动态排序 #{} ${}问题
Android 中实现ListView滑动隐藏标题栏的代码
Android基本游戏循环实例分析
Android实现底部弹出的对话框功能
![](https://img.aspxhome.com/file/2023/2/138752_0s.jpg)
Java实现读取163邮箱,qq邮箱的邮件内容
![](https://img.aspxhome.com/file/2023/9/63159_0s.png)
Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数示例代码
![](https://img.aspxhome.com/file/2023/4/80224_0s.gif)