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

来源:互联网 发布:出国留学gpa算法 编辑:程序博客网 时间:2024/06/07 04:55

报错 :

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));}


操作完成 !


阅读全文
0 0
原创粉丝点击