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

Xamarin Forms从服务器下载APK到外部存储遇FileUriExposedException求助

解决Xamarin Forms中Android.OS.FileUriExposedException异常的方案

Android 7.0(API 24)及以上版本禁止跨应用直接使用file://类型的Uri访问文件,这是导致你遇到FileUriExposedException的核心原因。必须通过FileProvider生成content://类型的Uri来共享文件,具体解决步骤如下:

1. 在AndroidManifest.xml中注册FileProvider

打开Android项目的AndroidManifest.xml,在<application>标签内添加FileProvider配置:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

若项目使用旧版Android Support库,将androidx.core.content.FileProvider替换为android.support.v4.content.FileProvider

2. 创建共享路径配置文件

在Android项目的Resources目录下新建xml文件夹,然后创建file_paths.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_download" path="Download/MyAppApks/" />
</paths>

该配置指定了允许共享的外部存储目录,对应你代码中存放APK的Download/MyAppApks文件夹。

3. 修改启动安装的代码逻辑

替换原代码中生成Uri和启动Intent的部分,改用FileProvider生成合法Uri并添加访问权限:

var intent = new Intent(Intent.ActionView);
// 通过FileProvider生成content://类型的Uri
var apkUri = FileProvider.GetUriForFile(Android.App.Application.Context, 
    $"{Android.App.Application.Context.PackageName}.fileprovider", apkFile);
intent.SetDataAndType(apkUri, "application/vnd.android.package-archive");
// 授予临时读取权限
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);

完成以上三步后,即可正常启动APK安装流程,不会再抛出FileUriExposedException异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:47:32