Android 7.0 在安装更新的APK时报错:android.os.FileUriExposedException:

在项目中按照以前的更新方法进行更新的时候就报了这个错误,原因是Android 7.0 权限更改导致,确切的说是 Android 对权限的进一步管理。

具体的报错为:

android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.hq.dis.deb/cache/hos_doc.apk exposed beyond app through Intent.getData()

 

我的解决方案:

1.在AndroidManifest.xml中添加如下代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

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

2.在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path 
        name="external_files" 
        path="."/>
</paths>

3.修改代码

File file = new File(AppPathUtil.getParentFile(getContext()), "hos_doc.apk");
String applicationId = BuildConfig.APPLICATION_ID;
Intent intent = new Intent(Intent.ACTION_VIEW);
// Android 7.0 系统共享文件需要通过 FileProvider 添加临时权限,否则系统会抛出 FileUriExposeException 异常
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 判断是否是AndroidN以及更高的版本
    Uri contentUri = FileProvider.getUriForFile(getActivity(), applicationId + ".provider", file);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(Uri.parse("file://" + apkFilePath), "application/vnd.android.package-archive");
}
getActivity().startActivity(intent);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值