日常代码记录

解决:Android N (7.0)上 android.os.F

2017-07-07  本文已影响100人  jiongge

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中添加如下代码

<application……
      <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xxx.saturn.apkfileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/apk_file_provider" />
        </provider>
    </application>

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

2、res路径下新建xml文件添加如下文件(文件名为上面的apk_filr_provider)

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-cache-path name="newest_apk" path="" />
</paths>

path:需要临时授权访问的路径(.代表所有路径) (我这边是没有写内容,但是网上的一些朋友说不写会报错)
name:就是你给这个访问路径起个名字

3、在打开新下载的安装包的地方修改代码

Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "com.iboxpay.saturn.apkfileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

        startActivity(intent);

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

加上写的比较好的几个链接
Android7.0须知--应用间共享文件FileProvider
[Android 7.0 FileUriExposedException 解决,支持新浪微博](Android 7.0 FileUriExposedException 解决,支持新浪微博);
Android7.0拍照失败FileUriExposedException,你的拍照代码升级了吗

上一篇 下一篇

猜你喜欢

热点阅读