1、在AndroidManifest.xml中添加如下代码
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" ... <application ... <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider> </application> </manifest>
2、在res目录下新建一个xml文件夹,并且新建一个provider_paths的xml文件
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>
注意
external-path代表了不同的文件目录,一共有五种,下面是官网的说明:
<files-path name="name" path="path" />
files/
subdirectory of your app's internal storage area. This subdirectory is the same as the value returned by
Context.getFilesDir()
.
Context.getFilesDir()
.
<cache-path name="name" path="path" />
getCacheDir()
.
<external-path name="name" path="path" />
Environment.getExternalStorageDirectory()
.
<external-files-path name="name" path="path" />
Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)
.
<external-cache-path name="name" path="path" />
Context.getExternalCacheDir()
.
3、修改代码
Uri photoURI = Uri.fromFile(createImageFile());
变成:Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());