解决Android 7.0及以上版本文件暴露异常exposed beyond app through Intent.getData()的方法

转载:https://www.icode9.com/content-4-619191.html

 

我们在APP升级的时候进行下载安装,却在Android 7.0及以上版本会报错

 android.os.FileUriExposedException: file:///路径 exposed beyond app through Intent.getData()

我们可以借助FileProvider来解决这个问题

1.新建一个filepaths

在项目的res文件夹下新建一个xml文件夹,在xml文件夹新建一个.xml文件

filepaths.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

2.修改AndroidManifest

在AndroidManifest的Application标签下新增provider标签

<application
       ......
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
        <activity
        .......
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.ice.AAAAA.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"
                />
        </provider>
    </application>

3.java代码

当apk下载好之后启动安装

 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

 Uri uri;
 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     //记得修改com.xxx.fileprovider与androidmanifest相同
     uri = FileProvider.getUriForFile(mContext,"com.ice.AAAAA.fileprovider",apkFile);
     intent.setDataAndType(uri,"application/vnd.android.package-archive");
 }else{
     uri = Uri.parse("file://" + apkFile.toString());
 }
 intent.setDataAndType(uri, "application/vnd.android.package-archive");
 mContext.startActivity(intent);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值