.NET MAUI

Introduction

You might have noticed that in many Android apps, you need to tap the back button twice to exit. When you tap it once, a message pops up. But if you tap it twice at the same time, you can close the app.

Before Android 13 (which is like the newest version), we used to make this work by changing how the back button behaves in the main part of the app (we call it "MainActivity"). But now, with Android 13, the way we used to do this is not recommended anymore. They have a new method that's better.

Table of content

Project Setup

Implementation

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?.Navigation;
		if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
		{
			const int delay = 2000;
			if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
			{
				activity.FinishAndRemoveTask();
				Process.KillProcess(Process.MyPid());
			}
			else
			{
				Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
				backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
			}
		}
	}
}
protected override void OnCreate(Bundle? savedInstanceState)
{
	base.OnCreate(savedInstanceState);
    OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
}

Full Code

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
using AndroidX.Activity;

namespace MauiOnBackPressed;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity: MauiAppCompatActivity
{
    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
    }
}
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?.Navigation;
        if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
        {
            const int delay = 2000;
            if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
            {
                activity.FinishAndRemoveTask();
                Process.KillProcess(Process.MyPid());
            }
            else
            {
                Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
                backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            }
        }
    }
}

Download Code

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article and it is useful to you, do like, share the article & star the repository on GitHub.

Reference