解决安装APK报FileUriExposedException

今天把sdk版本调高了然后安装APK报这个错,手机写的可能排版有点乱,记录一下,将就看吧!

android.os.FileUriExposedException: file:///storage/emulated/0/xxx/xxx.apk exposed beyond app through Intent.getData()

代码是这样的

Intent intent =new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + str), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

这个代码在7.0以下使用是没问题的,但是在8.1或以上用就会报错

解决方法:
1.在xml文件里新建一个file_paths.xml文件内容如下

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="apk" path="xiaokang/安装包"/></paths>

name我也不知道什么应该百度搜得到想了解的去百度看看,path是路径也就是/sdcard/xiaokang/安装包这个目录

2.在AndroidMainfest.xml里添加下面的代码

<provider
            android:name="android.support.v4.content.FileProvider"            android:authorities="自己的包名.fileprovider"            android:exported="false"            android:grantUriPermissions="true">         <meta-data        android:name="android.support.FILE_PROVIDER_PATHS"        android:resource="@xml/file_paths" />            ...        </provider>

3.下面是适配的代码

Intent intent = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);    Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apk_file);    intent.setDataAndType(uri, "application/vnd.android.package-archive");} else {    intent.setDataAndType(Uri.fromFile(apk_file), "application/vnd.android.package-archive");}context.startActivity(intent);

这样就能解决这个问题了!

即使这样我的还是报了这个错
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/xxx/xxx.apk

解决方法
在file_paths文件里添加下面代码

<root-path name="root_path" path="."/>

我这个也是转载的,结合以下两篇文章
1.https://www.kaelli.com/18.html
2.https://www.jianshu.com/p/167cf6c5dfa5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值