I’ve recently started a project in MAUI, and I’m trying to figure out how to simplify the update process (the app is not on the store, it's a private project).
Currently, I’m able to download the APK with the new version of the app from a database, but once it’s downloaded, I don’t understand how to activate the APK to perform the update.
So far, I’ve followed this logic, but the code shows several errors, and when it’s executed, nothing happens at all (not even an error message).
public void ActivateApk(string apkFilePath)
{
if (string.IsNullOrWhiteSpace(apkFilePath))
{
DisplayAlert("Errore", "Percorso del file APK non valido.", "OK");
return;
}
try
{
if (!File.Exists(apkFilePath))
{
DisplayAlert("Errore", "Il file APK specificato non esiste.", "OK");
return;
}
var intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Android.Net.Uri.Parse(apkFilePath), "application/vnd.android.package-archive");
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission);
Platform.CurrentActivity.StartActivity(intent);
}
catch (Exception ex)
{
DisplayAlert("Errore", $"Errore durante l'attivazione del file APK: {ex.Message}", "OK");
}
}
First, please add the following permission in the AndroidManifes.xml:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
And then create the provider_paths.xml
below the \Platforms\Android\Resources\xml folder and add the following code:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>
Finally, you can install the new version applicaion by the following code:
var context = Android.App.Application.Context;
Java.IO.File file = new Java.IO.File(apkFilePath);
using (Android.Content.Intent install = new Android.Content.Intent(Android.Content.Intent.ActionView))
{
Android.Net.Uri apkURI = AndroidX.Core.Content.FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);
install.SetDataAndType(apkURI, "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);
}