Android 7.0為了提高私有文件的安全性進(jìn)行了系統(tǒng)權(quán)限更改。當(dāng)嘗試把file://URI發(fā)到應(yīng)用外會(huì)觸發(fā)FileUriExposedException驻呐,官方推薦方法是使用FileProvider楼入。(詳情:https://developer.android.com/reference/android/support/v4/content/FileProvider.html)
使用方法:
1,在AndroidManifest.xml配置FileProvider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xxx.xxx.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path" />
</provider>
這里需要把com.xxx.xxx改成自己應(yīng)用的包名。
2迂尝,在資源文件的xml目錄下創(chuàng)建file_path.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<root-path
name="file_path"
path="."/>
</paths>
3,生成Uri
Uri uri = FileProvider.getUriForFile(context, "com.xxx.xxx.fileprovider", file);
第二個(gè)參數(shù)authority要和第一步的配置里android:authorities的值保持一致。