关于Android 7.0 系统处理文件FileUriExposedException的问题

参考内容:http://www.cnblogs.com/yongdaimi/p/6067319.html
今天华为手机报错了,安装APK更新的时候闪退,一直以为是华为手机的问题,结果是发现其实是安卓7.0的问题,之所以其他机型没出问题是因为市场上华为手机最多,也是最快更新了7.0系统。通过查找资料,发现这是和系统权限有关,找到以下解决方法

AndroidManifest.xml 中,在Application节点下添加

   <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是我们接下来要添加的文件

添加文件 file_paths:

Paste_Image.png
<?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:就是你给这个访问路径起个名字

public static void installApkFile(Context context, String filePath) {
        Intent intent = new Intent(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, "包名.fileprovider", new File(filePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
    } else {
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    context.startActivity(intent);
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容