android 调用相机问题

问题

调用相机时

private static final int TAKE_PICTURE = 0;
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);

可能会报以下错误

android.os.FileUriExposedException: file:///storage/emulated/0/cache.jpg exposed beyond app through ClipData.Item.getUri()

解决方法

使用FileProvider解决

1、先在src/main/res/xml创建file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <root-path name="root_path" path="."/>
        <external-path path="Android/data/${applicationId}/"
            name="camera_photos" />
    </paths>
</resources>
2、在AndroidManifest.xml进行配置
<application>
<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
</application>
3、在原来调用相机的Activity中修改代码
private static final int TAKE_PICTURE = 0;
File file = new File("image.jpg");
Uri imageUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID+".provider", file);
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);

其他问题

另外要提一下,某些同学会在写file_paths.xml这一步中可能会不写<root-path>这一标签,但是如果去缺少这一标签可能会造成以下错误:

java.lang.IllegalArgumentException: Failed to find configured root that contains /image.jpg

这是共享SD卡时发生的错误,加上<root-path>这一标签就可以解决了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值