简介
从Android 7.0开始,Android不再允许在app中把file://Uri暴露给其他app,包括但不局限于通过Intent或ClipData 等方法。原因在于使用file://Uri会有一些风险,
google推荐使用FileProvider来生成一个content://Uri格式的URI替代file://Uri
。
解决方法
- 首先在res/xml/目录下添加provider_paths.xml 文件
然后在AndroidManifest.xml配置文件
中添加provider配置信息- 在代码里使用
FileProvider.getUriForFile
()方法获得Url
添加provider_paths.xml 文件
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="images/"/>
</paths>
在AndroidManifest.xml配置文件
中添加provider配置信息
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.myapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true"> <meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
代码里使用
String filePath = Environment.getExternalStorageDirectory() + "/images/"+System.currentTimeMillis()+".png";
File outputFile = new File(filePath);
Uri imageUri;
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.N){
imageUri = FileProvider.getUriForFile(MainActivity.this,
"com.example.myapplication.fileprovider",outputFile);
}else {
imageUri = Uri.fromFile(outputFile);
}