.net-6.0mauiandroid-fileprovider

.NET MAUI FileProvider on Android does not work in release mode


I am attempting to install an apk file using .NET MAUI on an Android device like so:

var bytes = DownloadApkFile();
var file = Path.Combine(FileSystem.Current.CacheDirectory, "app.apk");
File.WriteAllBytes(file, bytes);

var context = Android.App.Application.Context; 
Java.IO.File file = new Java.IO.File(path);
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", file);
     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);
}

This works perfectly in debug mode, but in release mode I get the following exception: Java.Lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.mycompany.mobile.fileProvider

I thought maybe I needed to add a [ContentProvider] attribute to the application, but then it no longer builds because of duplicate content providers for androidx.core.content.FileProvider, so I assume MAUI is including this content provider automatically?


Solution

  • The Android/iOS linkers are removing chunks of the assemblies of your app due to the heavy use of reflection. You can verify this by adding code as follows in the csproj file as follows :

    <PropertyGroup>
        <AndroidLinkMode>None</AndroidLinkMode>
    </PropertyGroup>
    

    And you can also instruct the linker to keep some of the important assemblies .

    The steps are as follows: :

    1. Add an XML file named Linker.xml to your Android project.
    2. Right click Linker.xml in your Solution Explorer then select Properties.
    3. Change Build Action to LinkDescription.

    There is a simimar thread,you can check it here Linker.