FileUriExposedException: file:///storage/emulated/0/Android/data/com.skyrin.bingo/cache/app/app.apk

安卓在app更新的时候file parseuri 报错FileuriExposedException:.................exposed beyond app through Intent.getData();

执行下面代码报错的

Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
File file = new File(path);
Uri uri = Uri.fromFile(file);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
this.startActivity(intent);

 

原因:

这个问题是由于 Android 7.0 权限更改导致,确切的讲是 Android 对权限的进一步管理,从 Android 6.0 的动态权限申请

解决方法:

1.在mainfest清单文件下添加

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

2.res/xml目录下创建文件 file_paths.xml 内容如下:

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

 

<external-cache-path> 表示应用程序内部存储目录下的 cache/ 目录,完整路径为 Android/data/com.xxx.xxx/cache/
path 属性用于指定子目录。
name 属性告诉 FileProvider 为 Android/data/com.xxx.xxx/cache/app/ 创建一个名为 apk 的路径字段。
通过如上设置之后,当我们为 app.apk 请求 URI 时,FileProvider 就能根据配置返回如下 URI 了:
content://com.skyrin.bingo.fileprovider/apk/app.apk

修正以后的代码为:

File apkFile = new File(getExternalCacheDir()+"/app/face.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
//Android 7.0 系统共享文件需要通过 FileProvider 添加临时权限,否则系统会抛出 FileUriExposedException .
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri contentUri = FileProvider.getUriForFile(this,"com.skyrin.bingo.fileprovider",apkFile);
    intent.setDataAndType(contentUri,"application/vnd.android.package-archive");
}else {
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(
            Uri.fromFile(apkFile),
            "application/vnd.android.package-archive");
}
this.startActivity(intent);

 

问题解决

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值