自Android 7.0以上系統版本,如果應用A本身文件提供給其它應用B使用時,如果應用B沒有該文件的讀寫權限,就會拋出FileUriExposedException。例如APP保存一張圖片,通過Intent啓動把圖片的URI傳遞給系統圖片查看軟件,就會出現異常。谷歌推薦解決方式通過FileProvider的方式。具體如下:
(1)在清單文件<application>標籤中加入:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="app的包名.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
(2)配置file_paths.xml文件,如下是示例代碼
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path
name="test"
path="" />
</paths>
</resources>
其中<paths>中對應4中標籤分別對應的目錄如下:
files-path —Context.getFilesDir()
cache-path — Context.getCacheDir()
external-path — Environment.getExternalStorageDirectory()
external-files-path— Context.getExternalFilesDir()
external-cache-path— Context.getExternalCacheDir()
(3)FileProvider在java中的使用
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context,
"app的包名.fileprovider",file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(tempFile);
}
addUiIntentFlags(intent);
intent.setDataAndType(uri, mimeType);
startActivity(intent);