安卓8.0开始不能够再用
Uri.fromFile();获得uri,今天为了适配这个bug,在网上找了很多方案,但是写的都不是很完善,所以把自己今天解决这个bug的流程写下来
一、配置manifest,在manifest里面加入如下代码
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:grantUriPermissions="true" android:exported="false"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/filepaths" /> </provider>
二、在之前Uri.fromFile()处用如下代码替换
Uri uri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName()+".fileprovider"/*此处是为了和manifest一致*/, new File(outputFilePath)); } else { uri = Uri.fromFile(new File(outputFilePath)); }
三、在res目录xml下添加filepaths.xml
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-files-path name="files" path="photos" /> <external-path name="files" path="photos" /> <root-path path="" name="camera_photos" />/*必须,不然会报java.lang.IllegalArgumentException: Failed to find configured root错误*/ </paths>
至此大功告成!