参考资料:
http://www.jianshu.com/p/ba57444a7e69
http://blog.csdn.net/Chay_Chan/article/details/57083383
由于从Android7.0开始,直接使用真实的路径的Uri会被认为是不安全的,会抛出一个FileUriExposedException这样的异常。需要使用FileProvider,选择性地将封装过的Uri共享到外部。
由于FileProvider是继承ContentProvider,属于四大组件之一,需要在AndroidManifest.xml中配置,配置如下:
<!--版本更新所要用到的 fileProvider 用于兼容7.0通知栏的安装-->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<!--元数据-->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_paths"/>
</provider>
${applicationId}是获取当前项目的包名,前提是defaultConfig{}闭包中要有applicationId属性。
defaultConfig {
applicationId "com.jimtrency.lh.weixinimageselector"
minSdkVersion 14
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
在res资源目录下新建xml文件下,在该文件夹下创建file_provider_paths.xml文件,这个xml文件名并不是一定要这么起,只要和清单文件中配置的文件名一致就行。
那,<paths></paths>
下的字段都是什么意思呢?
//getFilesDir() (/data/data//files目录)
1.<files-path>
//getCacheDir() (/data/data//cache目录)
2.<cache-path>
// Environment.getExternalStorageDirectory()
3.<external-path>
// Context.getExternalFilesDir(String).
4.<external-files-path>
// Context.getExternalCacheDir()
5.<external-cache-path>
path :代表设置的目录下一级目录
eg:<external-path path="images/"
整个目录为:
Environment.getExternalStorageDirectory()+”/images/”
上述代码中path=”“,是有特殊意义的,它代码根目录,也就是说你可以向其它的应用共享根目录及其子目录下任何一个文件了,如果你将path设为path=”pictures”, 那么它代表着根目录下的pictures目录(eg:/storage/emulated/0/pictures),如果你向其它应用分享pictures目录范围之外的文件是不行的。