在Android 7.0 以上 对图片进行裁剪适配的报错

报错 :

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


主要是由于在Android 7.0以后,用了Content Uri 替换了原本的File Uri,故在targetSdkVersion=24的时候,部分 “Uri.fromFile()“
方法就不适用了。 **File Uri 与 Content Uri 的区别** - File Uri 对应的是文件本身的存储路径 - Content Uri 对应的是文件在Content
Provider的路径 所以在android 7.0 以上,我们就需要将File Uri转换为 Content Uri
具体解决 有两种方法

方法 一 : 出自github ; 我就不做赘述了 .


方法 二 : 我自己使用的是这种方法

step 1 在AndroidManifest. xml中添加如下代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>
 

step 2 在res目录下新建一个xml文件夹 , 并且新建一个provider_paths的xml文件

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


step 3 修改拍照时的参数

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile( context ,getApplicationContext().getPackageName()
+
".provider" , tempFile)); //Uri.fromFile(tempFile)


备注 考虑版本兼容可以如下操作
int currentapiVersion = Build.VERSION.SDK_INT;
if (currentapiVersion < 24){
    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));  
}else{  //解决Android 7.0 相机问题
    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getApplicationContext(),
            getApplicationContext().getPackageName()+ ".provider", tempFile));
}


操作完成 !


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值