关于Android7.0及以上版本FileUriExposedException的问题

在开发读取本地图片的功能时,使用了Uri.fromFile(path); 在7.0以下版本是没有问题的,但是在7.0及以上版本则会报出FileUriExposedException,这是Google为了安全考虑,做出的调整,同时也给出了对应的解决办法。

办法一:使用FileProvider

在清单文件中的application节点下添加

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

其中xxx最好用包名来标识,在file_paths.xml中编写该Provider对外提供文件的目录。

使用时:打开照相机

File file = new File(path);

  // 第二个参数是manifest中定义的`authorities`

Uri uri = FileProvider.getUriForFile(context, "xxx.fileprovider", file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
...... 其他参数

intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

//给目标一个临时的授权。
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);


办法二:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
file
));
        startActivityForResult(intent, TAKE_PHOTO_REQ_CODE);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值