.NET MAUI Android平台FileProvider在Release模式下失效
.NET MAUI Release模式下安装APK报错的解决方法
问题原因
Debug模式正常但Release模式抛出Java.Lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.mycompany.mobile.fileProvider,核心原因:
- MAUI确实会自动注册
androidx.core.content.FileProvider,但Release模式下ProGuard混淆会移除FileProvider的元数据或相关类 - 缺少指定共享文件路径的配置文件,导致系统无法识别FileProvider的权限范围
解决步骤
1. 创建文件路径配置文件
在Platforms/Android/Resources目录下新建xml文件夹,然后创建file_paths.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 对应代码中使用的CacheDirectory,允许访问缓存目录下的所有文件 --> <cache-path name="cache" path="." /> </paths>
2. 修正AndroidManifest.xml配置
在Platforms/Android/AndroidManifest.xml的<application>标签内添加(或修正)FileProvider配置,确保权限与代码中的一致:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileProvider" android:exported="false" android:grantUriPermissions="true" tools:replace="android:authorities"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
注意:需确保
AndroidManifest.xml根标签已引入tools命名空间:xmlns:tools="http://schemas.android.com/tools",否则tools:replace属性会报错
3. 添加ProGuard规则防止混淆
在Platforms/Android目录下创建proguard.cfg文件(已有则直接编辑),添加以下规则:
-keep class androidx.core.content.FileProvider { *; } -keep class android.support.v4.content.FileProvider { *; } -keepattributes *Annotation*
接着在项目.csproj文件的Release配置组中添加:
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <AndroidProguardEnabled>True</AndroidProguardEnabled> <AndroidProguardConfiguration>proguard.cfg</AndroidProguardConfiguration> </PropertyGroup>
4. 修正代码中的变量重复问题
代码存在变量名重复的问题,将第二个file变量重命名,避免编译警告:
var bytes = DownloadApkFile(); var apkPath = Path.Combine(FileSystem.Current.CacheDirectory, "app.apk"); File.WriteAllBytes(apkPath, bytes); var context = Android.App.Application.Context; Java.IO.File javaFile = new Java.IO.File(apkPath); using (Android.Content.Intent install = new Android.Content.Intent(Android.Content.Intent.ActionView)) { var uri = Microsoft.Maui.Storage.FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileProvider", javaFile); install.SetDataAndType(uri, "application/vnd.android.package-archive"); install.AddFlags(Android.Content.ActivityFlags.NewTask); install.AddFlags(Android.Content.ActivityFlags.GrantReadUriPermission); install.AddFlags(Android.Content.ActivityFlags.ClearTop); install.PutExtra(Android.Content.Intent.ExtraNotUnknownSource, true); Platform.CurrentActivity.StartActivity(install); }
内容的提问来源于stack exchange,提问作者MrZander
相关产品推荐
相关产品推荐

