You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android出现FileUriExposedException,配置FileProvider仍崩溃求助

解决FileUriExposedException问题

你已经配置了FileProvider,但代码中仍在使用Uri.fromFile(file)生成file://格式的Uri,这在Android 7.0(API 24)及以上版本会触发FileUriExposedException——系统禁止直接暴露文件路径给其他应用。

修正后的openDownloadedFile函数:

fun openDownloadedFile(context: Context?, fileName: String) {
    val storageDirectory = Environment.getExternalStorageDirectory().toString() + STORAGE_DIRECTORY + "/${fileName}"
    val file = File(storageDirectory)

    if (file.exists() && context != null) {
        // 用FileProvider生成Content Uri替代file:// Uri
        val downloadedFileUri = FileProvider.getUriForFile(
            context,
            "net.mytvplus.stbstore.file_provider", // 与manifest中声明的authorities完全一致
            file
        )
        
        val fileIntent = Intent(Intent.ACTION_VIEW)
        fileIntent.setDataAndType(downloadedFileUri, "application/vnd.android.package-archive")
        // 授予目标应用临时读取权限
        fileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        fileIntent.flags = fileIntent.flags or Intent.FLAG_ACTIVITY_NEW_TASK
        
        context.startActivity(fileIntent)
    }
}

关键修改说明:

  • 替换Uri.fromFile(file)为FileProvider.getUriForFile(),传入Context、manifest配置的authorities和目标文件
  • 添加Intent.FLAG_GRANT_READ_URI_PERMISSION,允许其他应用临时访问该文件
  • 补充context != null判空,避免空指针异常

你的file_provider.xml配置已经覆盖了整个外部存储,路径范围是合法的,无需修改。

内容的提问来源于stack exchange,提问作者Roony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 17:17:06