Riporto la soluzione che ho trovato, sperando possa essere utile anche ad altri.
in MainActivity.cs (Progetto Android)
using Android.App;
using Android.Content.PM;
using Android.OS;
using AndroidX.Activity;
using AndroidX.Activity.OnBackPressed;
using Xamarin.Forms;
namespace YourAppNamespace.Droid
{
[Activity(Label = "YourApp", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
Xamarin.Forms.Forms.Init(this, savedInstanceState);
// Configura il dispatcher per il tasto Indietro
var callback = new CustomOnBackPressedCallback(this, true);
OnBackPressedDispatcher.AddCallback(this, callback);
LoadApplication(new App());
}
private class CustomOnBackPressedCallback : OnBackPressedCallback
{
public CustomOnBackPressedCallback(MainActivity activity, bool enabled) : base(enabled) { }
public override void HandleOnBackPressed()
{
MessagingCenter.Send("BackButtonPressed", "BackButtonPressed");
}
}
}
}
Nella pagina principale dell'app (Progetto Condiviso)
using Xamarin.Forms;
namespace YourAppNamespace
{
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
// Ascolta il messaggio "BackButtonPressed"
MessagingCenter.Subscribe<string>(this, "BackButtonPressed", async (sender) =>
{
await HandleBackButtonAsync();
});
}
private async Task HandleBackButtonAsync()
{
if (Navigation.NavigationStack.Count > 1)
{
await Navigation.PopAsync();
}
else
{
bool exit = await DisplayAlert("Esci", "Vuoi davvero uscire dall'app?", "Sì", "No");
if (exit)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
}
}
}
}