How to get hardware back button working on Prism Maui

41 Views Asked by At

I am working on trying to get the android hardware back button working on a prism Maui application. This appears to have been an issue for a while, and is possibly still one. (Please correct me if I am wrong.) I have been looking for work-arounds in order to get this working, and I found this one Here However, this is for an older version of the library, and if I use my current base page ("Login") in my PrismStartup class without a navigation page I get undesirable results. However, I think this is a step in the right direction. Therefore Nevertheless, I have provided my code and maybe there is something here that can be done, but I just don't see it. Here is my code for my app builder:

        var builder = MauiApp.CreateBuilder()
            .....
            .UseMauiApp<App>()
            .ConfigureEffects(effects =>
            {
                effects.Add<DynamicClickEffect, DynamicClickEffectImp>();
            }).ConfigureLifecycleEvents(builder => {
#if ANDROID
                builder.AddAndroid(android => {
                    android.OnBackPressed(activity => true);
                });
#endif
            })
            .UsePrism(PrismStartup.Configure)
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

Here I also added the following line to some application pages for testing on their individual ContentPage classes:

protected override bool OnBackButtonPressed() => true;

And here is my prism start class within my MauiProgram.cs file that has the navigation page removed as pointed out in the workaround above.

internal static class PrismStartup
{
    public static void Configure(PrismAppBuilder builder)
    {
        builder.RegisterTypes(RegisterTypes).CreateWindow(navigationService =>
        {
            var builder = navigationService.CreateBuilder();

            builder.AddSegment("/Login");

            return builder.NavigateAsync();
        });
    }

    private static void RegisterTypes(IContainerRegistry containerRegistry)
    {
        //...
    }
}

Other than using the code that I have, is it possible to perhaps use something that is invoked on the main activity? By perhaps using something along the lines of:

class BackPress : OnBackPressedCallback
{
    private readonly Activity activity;
    private long backPressed;

    public BackPress(Activity activity) : base(true)
    {
        this.activity = activity;
    }

    public override void HandleOnBackPressed()
    {
        var navigation = Microsoft.Maui.Controls.Application.Current?.MainPage;
        var navPage = (NavigationPage)navigation;

        //... Do something here

    }
}

Any guidance on how to handle this would be much apreicated. Thanks.

0

There are 0 best solutions below