MAUI Lifecycle APIs
Understanding the application and page lifecycle in .NET MAUI is crucial for managing resources, handling state, and ensuring a smooth user experience. This section details the key lifecycle events and APIs available.
Application Lifecycle
The application lifecycle events are managed by the MauiApp
class and its associated delegates. These events fire when the application starts, becomes active, goes into the background, or is terminated.
Key Application Events:
OnLaunched()
: Called when the application is first launched. This is where you typically set up your initial UI and services.OnActivated()
: Called when the application is activated from a background state.OnDeactivated()
: Called when the application is deactivated and moves to the background.OnResumed()
: Called when the application is resumed from a background state.OnSleep()
: Called when the application is going to sleep, typically when the user navigates away from it or locks the device.OnSleepFinished()
: Called after the application has finished sleeping.OnBackgrounding()
: Called when the application is about to be backgrounded.OnBackgroundingFinished()
: Called after the application has finished backgrounding.OnBackgrounded()
: Called after the application has successfully been backgrounded.OnDestroying()
: Called when the application is being destroyed.
Example Application Startup:
public class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
// Register services here
return builder.Build();
}
}
public partial class App : Application
{
public App()
{
InitializeComponent();
// Set the MainPage here, or use navigation services
MainPage = new NavigationPage(new Views.MainPage());
}
protected override void OnLaunched()
{
base.OnLaunched();
System.Diagnostics.Debug.WriteLine("Application launched!");
// Perform any other startup tasks here
}
protected override void OnSleep()
{
base.OnSleep();
System.Diagnostics.Debug.WriteLine("Application is sleeping.");
// Save application state, close resources
}
protected override void OnResume()
{
base.OnResume();
System.Diagnostics.Debug.WriteLine("Application is resuming.");
// Restore application state
}
}
Page Lifecycle
Each page in your MAUI application has its own lifecycle events. These events allow you to manage the state and resources specific to individual pages.
Key Page Events:
OnAppearing()
: Called when the page is about to be displayed. This is a good place to load data or refresh UI elements.OnDisappearing()
: Called when the page is about to be removed from the screen. This is where you should release resources and save state.OnNavigatedTo(string id, bool isOnChildNavigation = false)
: Called after the page has been navigated to.OnNavigatedFrom(bool isOnChildNavigation = false)
: Called before the page is navigated from.OnNavigatingFrom(NavigatingFromEventArgs args)
: Called during the navigation process, allowing cancellation.
OnAppearing()
are properly released in OnDisappearing()
to prevent memory leaks.
Example Page Implementation:
public partial class DetailPage : ContentPage
{
private int counter = 0;
public DetailPage()
{
InitializeComponent();
BindingContext = new ViewModels.DetailViewModel();
System.Diagnostics.Debug.WriteLine("DetailPage initialized.");
}
protected override void OnAppearing()
{
base.OnAppearing();
System.Diagnostics.Debug.WriteLine("DetailPage is appearing.");
// Load data or update UI
counter = 0; // Reset counter for new appearance
}
protected override void OnDisappearing()
{
base.OnDisappearing();
System.Diagnostics.Debug.WriteLine("DetailPage is disappearing.");
// Clean up resources, save state
}
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
System.Diagnostics.Debug.WriteLine($"DetailPage navigated to. Query: {args.ExtraData}");
// Handle navigation parameters if any
}
protected override void OnNavigatedFrom(NavigatedFromEventArgs args)
{
base.OnNavigatedFrom(args);
System.Diagnostics.Debug.WriteLine("DetailPage navigated from.");
}
private void OnCounterClicked(object sender, EventArgs e)
{
counter++;
CounterLabel.Text = $"Clicked {counter} times";
SemanticScreenReader.Announce(CounterLabel.Text);
}
}
Platform-Specific Considerations
While MAUI provides a unified lifecycle model, the underlying native platforms (iOS, Android, Windows, macOS) have their own nuances. MAUI abstracts most of these, but it's good practice to be aware of potential differences, especially concerning background processing and resource management.