美文网首页Android开发经验谈Android开发Android技术知识
安装APK兼容Android7.x,解决FileUriExpos

安装APK兼容Android7.x,解决FileUriExpos

作者: 喜欢丶下雨天 | 来源:发表于2018-05-18 17:20 被阅读50次

问题

在Android7.x及以上手机中,安装APK会报错,如图:


屏幕快照 2018-05-18 下午3.41.17.png

解决方法

  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/provides_path" />
</provider>

说明:
authorities:app的包名.fileProvider
grantUriPermissions:必须是true,表示授予 URI 临时访问权限
exported:必须是false
resource:中的@xml/provides_path是我们接下来要添加的文件

  1. 在res目录下新建一个xml文件夹,并且新建一个provides_path的xml文件(如下图)


    屏幕快照 2018-05-18 下午5.08.32.png
  2. provides_path.xml文件里添加如下配置

<paths>
        <external-path
            name="beta_external_path"
            path="Download/"/>

        <external-path
            name="beta_external_files_path"
            path="Android/data/包名"/>

</paths>

说明:
name:就是你给这个访问路径起个名字
path:需要临时授权访问的路径

  1. 修改代码适配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);

相关文章

网友评论

    本文标题:安装APK兼容Android7.x,解决FileUriExpos

    本文链接:https://www.haomeiwen.com/subject/jrogdftx.html