解决 Android N 7.0 上 报错:android.os.FileUriExposedException

Posted ZeroFlutter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决 Android N 7.0 上 报错:android.os.FileUriExposedException相关的知识,希望对你有一定的参考价值。

解决 android N 上 安装Apk时报错:android.os.FileUriExposedException: file:///storage/emulated/0/Download/appName-2.3.0.apk exposed beyond app through Intent.getData()

解决方法

1、在AndroidManifest.xml中添加如下代码
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="app的包名.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
resource:中的@xml/file_paths是我们接下来要添加的文件

2、在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件(如下图)

3、打开file_paths.xml文件添加如下内容
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/app的包名/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>

path:需要临时授权访问的路径(.代表所有路径)
name:就是你给这个访问路径起个名字

4、修改代码适配Android N
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) 
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
 else 
    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

1、首先我们对Android N及以上做判断;
2、然后添加flags,表明我们要被授予什么样的临时权限
3、以前我们直接 Uri.fromFile(apkFile)构建出一个Uri,现在我们使用FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
4、BuildConfig.APPLICATION_ID直接是应用的包名

参考地址

以上是关于解决 Android N 7.0 上 报错:android.os.FileUriExposedException的主要内容,如果未能解决你的问题,请参考以下文章

已解决mac上appium报错:“Could not find aapt Please set the ANDROID_HOME environment variable with the And(代

Android N 7.0 出现 FileUriExposedException 异常的解决办法

报错修改:Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web

Android 7.0下,拍摄照片报错

Python3.7.0以上版本安装pip报错ModuleNotFoundError: No module named ‘_ctypes‘解决方法

SSL篇(7.0) 01. FortiClient 7.0报错-7200解决办法 ❀ 飞塔 (Fortinet) 防火墙