從Android 7.0開始,一個(gè)應(yīng)用提供自身文件給其它應(yīng)用使用時(shí),如果給出一個(gè)file://格式的URI的話,應(yīng)用會(huì)拋出FileUriExposedException。這是由于谷歌認(rèn)為目標(biāo)app可能不具有文件權(quán)限,會(huì)造成潛在的問題。所以讓這一行為快速失敗。
http://www.itdecent.cn/p/3f9e3fc38eae
1 FileProvider方式
這是谷歌官方推薦的解決方案。即使用FileProvider來生成一個(gè)content://格式的URI。具體實(shí)現(xiàn)方式如下:
manifest聲明
在manifest中聲明一個(gè)provider。name(即類名)為android.support.v4.content.FileProvider。
<manifest>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xx.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
...
</application>
</manifest>
其中authorities可以自定義。為了避免和其它app沖突,最好帶上自己app的包名。file_paths.xml中編寫該P(yáng)rovider對(duì)外提供文件的目錄。文件放置在res/xml/下。
2.編寫file_paths.xml
文件格式如下:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
...
</paths>
3.在Java代碼當(dāng)中使用
以分享一個(gè)圖片為例:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
phonePath=getImageTempPath();
//為了防止華為 酷派等一些手機(jī) 不能拍照的問題
File file=new File(phonePath);
file.createNewFile();
//7.0 FileUriExposedException 問題
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(getContext(), "org.xx.fileprovider", file);
} else {
uri = Uri.fromFile(file);
}
// 下面這句指定調(diào)用相機(jī)拍照后的照片存儲(chǔ)的路徑
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CAMERA);
通過FileProvider解決,實(shí)例下載:https://github.com/honjane/fileProviderDemo