android.os.FileUriExposedException异常,安卓7.0以后打开本地文件方式

本文介绍了解决Android 7.0以上版本对本地文件访问限制的两种方法:关闭URI暴露检测和更改URI获取方式。推荐使用后者,通过FileProvider组件及相应的配置文件实现更安全的文件分享。

android7.0以后对本地文件访问做了控制,会对uri进行暴露检测,针对此有两种解决办法

 

第一种:暴力解决办法,关闭uri暴露检测,在要使用的activity的onCreate方法中加入即可

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();

第二种:也是推荐的一种,更换uri的获取方式

1、在AndroidManifest中加入

<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>

2、res/xml/下面添加配置文件file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <external-path
            name="download"
            path=""/>
        <root-path
            name="root"
            path=""/>
        <files-path
            name="files"
            path=""/>

        <cache-path
            name="cache"
            path=""/>

        <external-path
            name="external"
            path=""/>

        <external-files-path
            name="external_file_path"
            path=""/>
        <external-cache-path
            name="external_cache_path"
            path=""/>

    </paths>
</resources>

3、代码中修改uri的获取方式

Uri.fromFile(file);

改为

public class FileProvider7 {

    public static Uri getUriForFile(Context context, File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = getUriForFile24(context, file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

    public static Uri getUriForFile24(Context context, File file) {
        Uri fileUri = android.support.v4.content.FileProvider.getUriForFile(context,
                context.getPackageName() + ".fileprovider",
                file);
        return fileUri;
    }
}

注意:这种方式在打开相应文件之前activity的设置,如下以打开本地图片为例

Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这行一定不能漏掉
Uri uri = FileProvider7.getUriForFile(AppContext.getInstance(), file);
intent.setDataAndType(uri, "image/*");

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值