解决 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中添加如下代码
"android.support.v4.content.FileProvider"    android:authorities="app的包名.fileProvider"    android:grantUriPermissions="true"    android:exported="false">    "android.support.FILE_PROVIDER_PATHS"        android:resource="@xml/file_paths" />

注意:
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"?>    "Android/data/app的包名/" name="files_root" />    "." name="external_storage_root" />

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直接是应用的包名

参考地址

更多相关文章

  1. Pycharm安装PyQt5的详细教程
  2. NPM 和webpack 的基础使用
  3. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  4. 如何将library项目打包成jar文件
  5. 《Android面试宝典》学习笔记(第五章:文件存储)
  6. IDA调试Android(安卓)so文件
  7. Android(安卓)studio使用SVN
  8. Android(安卓)Studio 开发–微信APP门户界面设计
  9. Android(安卓)关于arm64-v8a、armeabi-v7a、armeabi、x86下的so

随机推荐

  1. 什么是php扩展
  2. 在php中get和post区别
  3. php header的作用
  4. 什么是php工厂模式
  5. php join的用法
  6. php中define的用法
  7. asp与php网站优缺点
  8. php保留两位小数的方法
  9. php构造函数的作用
  10. 排序算法—归并排序【附代码】