解决Android7.0以上版本升级apk时报android.os.FileUriExposedException的问题

/Android6.0 以前升级apk用以下代码

  private void installApk() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

但是到了Android7.0 时,会报错这个错误:

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

下面,进行修复:
1. 在AndroidManifest.xml 的 application 里面添加以下代码

<application>
  ...
 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="yun.com.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
   </provider>
   ...
</application>

其中:exported必须为false,grantUriPermissions必须为true,authorities为”自己的包名.fileProvider”。

2. 在res目录下新建一个xml文件夹,再在xml文件夹里创建file_path.xml文件,添加以下代码

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <paths>
        <files-path path="Android/data/yun.com/" name="files_root" />
        <files-path path="." name="files_path" />
        <root-path path="." name="root"/>
        <external-path path="." name="files"/>
    </paths>
</paths>


这是apk默认保存路径String filePath = Environment.getExternalStorageDirectory();的时候使用的,若路径有修改,比如
String filePath = Environment.getExternalStorageDirectory() + "/Ccq";

那么,files-path也要做相应修改<files-path path="Android/data/yun.com/Ccq/" name="files_root" />

3. 最后一步,就是修改代码

 private void installApk() {
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context,  "yun.com.fileProvider", f);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        context.startActivity(intent);
    }

此时,应用是能正常升级版本的,但是,也有可能会发现,下载apk的进度条可能一直未0,也就是无法下载apk,这时可以去设置–权限设置里面把内部存储的权限打开,也可在代码中动态申请权限。还有一个方法,在APP的build.gradle文件中将 targetSdkVersion的版本降低。

这里写图片描述

技术浅陋,欢迎各位大神指正、补充。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值