Android7.0FileUriExposedException 问题解决

亦余心之所善兮,虽九死其犹未悔。这篇文章主要讲述Android7.0FileUriExposedException 问题解决相关的知识,希望能为你提供帮助。
一、  FileUriExposedException  的原因
【Android7.0FileUriExposedException 问题解决】android7.0不识别uri以file://开头,要将其转换为content://才能识别uri
二、如何解决
1.xml的创建:
file_paths.xml中编写该Provider对外提供文件的目录:文件放置在res/xml/下。  为了避免和其它app冲突,最好带上自己app的包名。
文件内容:

< ?xml version="1.0" encoding="utf-8"?>
< paths>
< external-path path="." name="external_storage_root" />
< /paths>

Android7.0FileUriExposedException 问题解决

文章图片

内部的element可以是files-path,cache-path,external-path,external-files-path,external-cache-path,分别对应Context.getFilesDir(),Context.getCacheDir(),Environment.getExternalStorageDirectory(),Context.getExternalFilesDir(),Context.getExternalCacheDir()等几个方法。后来翻看源码发现还有一个没有写进文档的,但是也可以使用的element,是root-path,直接对应文件系统根目录。不过既然没有写进文档中,其实还是有将来移除的可能的。使用的话需要注意一下风险。
2.Manifests.xml中配置
< manifest>
...
< application>
...
< provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${APPLICATION_ID}"
android:exported="false"
android:grantUriPermissions="true">
< meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
< /provider>

...
< /application>
< /manifest>
3.Uri使用
1)getUriForFile方法转换:
public static Uri getUriForFile(Context context, File file) {
return FileProvider.getUriForFile(context, GB.getCallBack().getApplicationId(), file);
}
//第二个参数是manifest中定义的`authorities`:因为当时file_paths.xml中赋值为.,故第二个参数是:"com.up366.mobile.fileProvider"
2)intent加Flags
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
注:获取本地图片,没有uri就不用写
完成。
 
 
 
 
 


    推荐阅读