doc/articles/features/hardware-back-button.md
Some devices provide a hardware back button to handle navigation within applications. SystemNavigationManager provides this functionality for Uno Platform applications.
The BackRequested event of the SystemNavigationManager is triggered whenever the user presses the hardware back button. To subscribe to it, first get an instance of SystemNavigationManager via the GetForCurrentView method:
var manager = SystemNavigationManager.GetForCurrentView();
manager.BackRequested += OnBackRequested;
The event handler should check whether the application can handle the back button press (e.g. if it is possible to navigate back within the app's UI), and in such case perform the in-app navigation and mark the event args as Handled:
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.CanGoBack)
{
this.Frame.GoBack();
e.Handled = true; // Indicates that the back request has been handled
}
}
[!NOTE] On Android 16+ (API level 36+), the behavior differs. See the Android 16+ behavior section below for details.
When Handled is set to true, the OS will not continue processing the request. If not set or set to false, the OS will navigate away from the application.
Make sure to unsubscribe from the event when no longer needed.
Starting with Android 16 (API level 36), the back navigation behavior has changed due to the predictive back gesture feature. On these versions, the Handled property is ignored, and the subscription state of the BackRequested event determines whether the app handles back navigation:
To ensure proper behavior on Android 16+, subscribe to BackRequested only when your app can handle back navigation, and unsubscribe when it cannot. A common pattern is to subscribe on Loaded and unsubscribe on Unloaded:
public MyPage()
{
InitializeComponent();
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested;
}
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.CanGoBack)
{
this.Frame.GoBack();
// The subscription itself indicates the app handles back navigation.
// So setting e.Handled has no effect and is ignored.
}
}
[!NOTE] On Android versions prior to 16, the
Handledproperty continues to work as expected. Setting it totrueprevents the OS from processing the back request, whilefalseallows the OS to handle it.