If your targetSdkVersion >= 24
, then we have to use FileProvider
class to give access to the particular file or folder to make them accessible for other apps.
(如果您的targetSdkVersion >= 24
,那么我们必须使用FileProvider
类来授予对特定文件或文件夹的访问权限,以使其他应用程序可以访问它们。)
We create our own class inheriting FileProvider
in order to make sure our FileProvider doesn't conflict with FileProviders declared in imported dependencies as described here . (我们创造我们自己的类继承FileProvider
,以确保我们的FileProvider并不冲突与进口的依赖声明FileProviders描述这里 。)
Steps to replace file://
URI with content://
URI:
(将file://
URI替换为content://
URI的步骤:)
Add a class extending FileProvider
(添加一个扩展FileProvider
的类)
public class GenericFileProvider extends FileProvider {}
Add a FileProvider <provider>
tag in AndroidManifest.xml
under <application>
tag.
(在AndroidManifest.xml
<application>
标记下添加FileProvider <provider>
<application>
标记。)
Specify a unique authority for the android:authorities
attribute to avoid conflicts, imported dependencies might specify ${applicationId}.provider
and other commonly used authorities. (为android:authorities
属性指定唯一的权限以避免冲突,导入的依赖项可能指定${applicationId}.provider
和其他常用权限。)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name=".GenericFileProvider"
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>
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
The final step is to change the line of code below in
(最后一步是更改下面的代码行)
Uri photoURI = Uri.fromFile(createImageFile());
to
(至)
Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
Edit: If you're using an intent to make the system open your file, you may need to add the following line of code:
(编辑:如果要使用意图使系统打开文件,则可能需要添加以下代码行:)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Please refer, full code and solution has been explained here.
(请参考,完整的代码和解决方案已在此处进行了说明。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…