Migrate the deprecated OnBackPressed function in .NET MAUI Android application

Migrate the deprecated OnBackPressed function in .NET MAUI Android application

29 September 2022

.NET MAUI/Xamarin

Buy Me A Coffee

Hello!

You must have noticed that in many Android apps, you can exit only after double-clicking on the back button. A toast message appears when you press the back button once. When you simultaneously press the back button you exit your apps.

This is usually implemented in MainActivity by overriding the OnBackPressed method. The code below demonstrates the possible implementation:

This worked great before Android 13 (SDK version 33). Starting from this release, OnBackPressed is deprecated.
Deprecated

So what is the alternative?

In Android 13, the new API is implemented to support predictive back gestures.

This feature will let a user preview the result of a Back gesture before they fully complete it - basically allowing them to decide whether to stay in the current view or complete the action and return to the Home screen, previous activity or a previously visited page in a WebView.
To support the predictive back gesture, Android 13 adds the new window-level OnBackInvokedCallback platform API. This API replaces the KeyEvent.KEYCODE_BACK API and all platform classes that use OnBackPressed.

Let's start with implementing OnBackPressedCallback:

You need to override the method HandleOnBackPressed. The content of this method is pretty much the same as in OnBackPressed.

In the final step, we need to add this callback. It can be done by overriding OnCreate method of MainActivity:

OnBackPressedDispatcher dispatches system back button pressed events to one or more OnBackPressedCallback instances.

Here is the result:
Back pressed in Android 33

Buy Me A Coffee

Related:

How to show SnackBar and Toast using Xamarin Community Toolkit

Demonstrate how to configure SnackBar and Toast using Xamarin Community Toolkit.

Azure Active Directory authentication in .NET MAUI

Create a small mobile application, which requires user authentication, using .NET MAUI (AD and AD B2C).

An unhandled error has occurred. Reload

🗙