安卓学习笔记---调用相机功能在安卓7.0以上报错android.os.FileUriExposedException

解决方法:

1.

在AndroidManifest.xml中添加如下代码
<!--解决在安卓7.0以上调用相机拍照出现android.os.FileUriExposedException 问题-->
<!--
注意:
  authorities:app的包名.fileProvider
  grantUriPermissions:必须是true,表示授予 URI 临时访问权限
   exported:必须是false
   resource:中的@xml/file_paths是我们接下来要添加的文件
-->
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="app的包名.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文件,里面内容如下
path:需要临时授权访问的路径(.代表所有路径) 
name:就是你给这个访问路径起个名字
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path path="." name="external_storage_root" />
</paths>

3.在需要打开相机时进行判断
//获取权限,打开照相机
private void openCamera() {
    Uri imageUri;
    //创建File对象,用于存储拍摄的照片
    File outputImage = new File(getPhotoPath());
    try {
        if (outputImage.exists()){
            outputImage.delete();
        }
        outputImage.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N){
        imageUri = FileProvider.getUriForFile(UserImageUpdateActivity.this,"app包名.fileprovider",outputImage);
    }else {
        imageUri = Uri.fromFile(outputImage);
    }
    //启动相机
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, REQUEST_CODE_FROM_CAMEIA);
}
// 拍照路径
public String getPhotoPath() {
    File file = new File(Constant.HEAD_PORTRAIT);
    if (!file.exists()) {
        file.mkdirs();
    }
    String path = file.getAbsolutePath() + "/userphoto.jpg";
    return path;
}

判断sdk版本,如果大于24,则使用provider,低于则使用应用关联缓存目录存下图片。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值