android S 上 安装apk出现android.os.FileUriExposedException

发布时间 2023-04-13 17:38:31作者: xiaowang_lj

报错:

android.os.FileUriExposedException: file:///data/user/0/com.example.overlay.   exposed beyond app through Intent.getData()

原因:

andorid7.0系统以后,引入“私有目录被限制访问”,“StrictMode API 政策”导致的问题。解决办法很简单。就是用新的方式获取uri。

” StrictMode API 政策” 是指禁止向你的应用外公开 file:// URI。 如果一项包含文件 file:// URI类型 的 Intent 离开你的应用,应用失败,并出现 FileUriExposedException 异常。

解决方法

1.在AndroidManifest.xml中添加如下代码

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.overlay.idea.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>

注意事项:
authorities:app的包名.fileProvider
grantUriPermissions:必须是true,表示授予 URI 临时访问权限 
exported:必须是false 为true则会报安全异常。
resource:中的@xml/file_paths是我们接下来要添加的文件

2、在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <root-path path="/data/user/0/com.example.overlay.idea/cache/" name="files_root" />
    <root-path path="." name="external_storage_root" />
</paths>

path:需要临时授权访问的路径(.代表所有路径)
name:访问路径名字

 

 

 

3.修改代码适配Android N

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.e(TAG, "installAPk: " + apkFile.getAbsolutePath());
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, "com.example.overlay.idea.fileprovider",apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

(308条消息) android安装apk出现android.os.FileUriExposedException_android.os.fileuriexposedexception: file:///storag_冬瓜去哪儿的博客-CSDN博客

Failed to find configured root that contains的解决办法不知道这里能帮到你吗 - 简书 (jianshu.io)