如何解决 android.os.FileUriExposedException 异常

介绍

在Android开发中,经常会遇到处理文件的情况,有时候我们需要向其他应用分享文件,这就涉及到文件URI的问题。然而,Android 7.0及以上版本引入了一项安全机制,即FileUriExposedException。当我们尝试通过文件URI暴露文件给其他应用时,系统会抛出此异常。本文将向您介绍如何解决 android.os.FileUriExposedException 异常。

解决方案概述

在解决该异常之前,我们需要了解整个过程的流程。下表展示了解决 android.os.FileUriExposedException 异常的步骤。

步骤 操作
Step 1 创建 FileProvider 内容提供器
Step 2 在 AndroidManifest.xml 文件中配置 FileProvider
Step 3 修改应用代码,使用 FileProvider 生成文件 URI

接下来,我们将详细介绍每一步需要做什么以及需要使用的代码。

Step 1: 创建 FileProvider 内容提供器

首先,我们需要创建一个 FileProvider 内容提供器来处理文件URI。以下是创建 FileProvider 的步骤:

  1. 在项目的 res 目录中创建一个新的目录,命名为 xml
  2. xml 目录中创建一个名为 file_paths.xml 的文件,并在其中添加以下内容:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="
    <external-path name="external_files" path="." />
</paths>

上述代码指定了要暴露的文件路径。

Step 2: 在 AndroidManifest.xml 文件中配置 FileProvider

接下来,我们需要在 AndroidManifest.xml 文件中配置 FileProvider,以便系统知道如何使用它。以下是配置步骤:

  1. application 标签内添加以下内容:
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.example.yourpackage.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

上述代码中,android:authorities 属性的值是您应用的包名加上 ".fileprovider"。android:resource 属性指定了刚才创建的 file_paths.xml 文件的路径。

Step 3: 修改应用代码,使用 FileProvider 生成文件 URI

最后,我们需要修改应用代码,使用 FileProvider 生成文件 URI。以下是修改代码的步骤:

  1. 导入所需的包:
import androidx.core.content.FileProvider;
  1. 替换现有代码中的 Uri.fromFile() 方法,使用 FileProvider.getUriForFile() 方法来生成文件 URI。以下是示例代码:
File file = new File(getFilesDir(), "my_file.txt");
Uri fileUri = FileProvider.getUriForFile(this, "com.example.yourpackage.fileprovider", file);

在上述代码中,getFilesDir() 返回应用的内部存储目录,替换为您实际使用的文件路径。"com.example.yourpackage.fileprovider"FileProvider 的授权名称,应与 AndroidManifest.xml 文件中的 android:authorities 属性的值相匹配。

通过上述步骤,我们成功解决了 android.os.FileUriExposedException 异常,并使用 FileProvider 安全地生成文件 URI。

结论

在本文中,我们解决了 android.os.FileUriExposedException 异常,并提供了详细的步骤来实现这一解决方案。通过使用 FileProvider,我们可以在Android 7.0及以上版本中安全地处理文件URI。希望这篇文章能帮助您解决该异常并提高您的开发效率。