In.NET MAUI, an application’s lifecycle management has a critical role in the application’s usage for the users. The application’s life cycle involves several events that occur as state transitions from one state to another such as when an app is started, stopped, resumed or destroyed. These lifecycle events are platform agnostic, let you create this same experience across multiple platforms using the same code base (Android, iOS, macOS, Windows, etc.).
Cross platform life-cycle hooks of.NET MAUI
The key lifecycle events in a .NET MAUI application are:
Created
: The application is created.Activated
: The application is in use and is on the screen or at least on the list of open and running programs.Deactivated
: The application is runnable but not visible on the screen at that particular time.Stopped
: It means that after using the application the user is unable to see it and it runs in the background.Resumed
: It continues after the user or the system paused or shuts the application down.Destroying
: The application is at an end typically through pressure from the available memory or the user ending the application.
To know more about these events let’s go deeper.
Created Event (Created
):
- Fired only once when the application is launched.
- Good when at the early stages of a resource or when establishing a service.
- Example Use: Starting of the basic elements of an application such as the databases, the logging frameworks, or the dependency injection services.
private void OnAppCreated(object sender, EventArgs e)
{
Console.WriteLine("App Created");
// Initialize essential services and dependencies
}
Activated Event (Activated
):
- Fired whenever the application’s window is brought to the front.
- That is why this event suggests that the user is interested in the application.
- Example Use: Retrieving the UI, continuing operation of tasks which were interrupted when application was not active.
private void OnAppActivated(object sender, EventArgs e)
{
Console.WriteLine("App Activated");
// Refresh UI or restart animations
}
Deactivated Event (Deactivated
):
- This event fires whenever the application is in the background but it still runs in memory.
- This happens before the application is moved to the background or merged to the application tray.
- Example Use: Suspending concurrent processes that ought not to be performing while the app is not in use.
private void OnAppDeactivated(object sender, EventArgs e)
{
Console.WriteLine("App Deactivated");
// Pause animations, save application state
}
Stopped Event (Stopped
):
- Started when the application is hidden from the foreground and minimized to the background.
- At this point the place where the application resides is almost invisible to the user.
- Example Use: As pointed out before, after some time we are saving the state of the application and stopping background activities to release memory.
private void OnAppStopped(object sender, EventArgs e)
{
Console.WriteLine("App Stopped");
// Save data to persistent storage or pause long-running operations
}
Resumed Event (Resumed
):
- Used when the application is returned from a Stopped of background state.
- Example Use: Downloading any updated data for those areas of the app that refresh their content when the app was not in the foreground.
private void OnAppResumed(object sender, EventArgs e)
{
Console.WriteLine("App Resumed");
// Reload data that may have changed while in the background
}
Destroying Event (Destroying
):
- This event is fired when the application is being shutdown, either because program is out of memory or the user made a quit command.
- Example Use: Unloading system resources like signing-off of opened database connections, writing final data at least twice to avoid loss.
private void OnAppDestroying(object sender, EventArgs e)
{
Console.WriteLine("App Destroying");
// Clean up resources, ensure all data is saved
}
It is better to write them down in the App class This class is defined in the file App.xaml.cs. If you want to access these lifecycle events, you may call the appropriate methods or use events being offered by the lifecycle of the application.
Application Class Lifecycle Events (App.xaml.cs)
The App
class provides event handlers to manage different lifecycle events:
All lifecycle events together
using Microsoft.Maui.LifecycleEvents;
namespace MauiAppExample
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
// Subscribe to lifecycle events
this.Created += OnAppCreated;
this.Resumed += OnAppResumed;
this.Stopped += OnAppStopped;
this.Activated += OnAppActivated;
this.Deactivated += OnAppDeactivated;
this.Destroying += OnAppDestroying;
}
private void OnAppCreated(object sender, EventArgs e)
{
Console.WriteLine("App Created");
// Code to initialize resources
}
private void OnAppResumed(object sender, EventArgs e)
{
Console.WriteLine("App Resumed");
// Code to refresh the UI, reload data
}
private void OnAppStopped(object sender, EventArgs e)
{
Console.WriteLine("App Stopped");
// Code to save application state, pause background tasks
}
private void OnAppActivated(object sender, EventArgs e)
{
Console.WriteLine("App Activated");
// Code to handle when the app becomes active (from inactive state)
}
private void OnAppDeactivated(object sender, EventArgs e)
{
Console.WriteLine("App Deactivated");
// Code to handle when the app is no longer in the foreground
}
private void OnAppDestroying(object sender, EventArgs e)
{
Console.WriteLine("App Destroying");
// Code to release resources, save data, etc.
}
}
}
Platform-Specific Lifecycle Events in .NET MAUI
What I like about platform specific lifecycle events is that it enables one to add flavor compatible with the particular platform and very important when it comes to creating consistent user experience or addressing platform issues.
The MauiProgram.cs file is the file used to setup and compile the MAUI program and it is into this specific file that platform-specific lifecycle events are set. Further, I’ll show how to attach to lifecycle events using Microsoft.Maui.LifecycleEvents on Android & iOS platforms.
The goal here is to capture specific platform lifecycle events, such as:
- Android: Stop- boost, continue app functional on creation.
- iOS: At the time of application launch, to re-sign the activation, and to become active once again.
Configure Platform-Specific Lifecycle Events in MauiProgram.cs
using Microsoft.Maui;
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Hosting;
using Microsoft.Maui.LifecycleEvents;
namespace MauiAppExample
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureLifecycleEvents(lifecycle =>
{
// Android-specific lifecycle events
#if ANDROID
lifecycle.AddAndroid(android =>
{
android.OnCreate((activity, bundle) =>
{
Console.WriteLine("Android: Application Created");
});
android.OnStart(activity =>
{
Console.WriteLine("Android: Application Started");
});
android.OnResume(activity =>
{
Console.WriteLine("Android: Application Resumed");
});
android.OnStop(activity =>
{
Console.WriteLine("Android: Application Stopped");
});
android.OnDestroy(activity =>
{
Console.WriteLine("Android: Application Destroyed");
});
});
#endif
// iOS-specific lifecycle events
#if IOS
lifecycle.AddiOS(ios =>
{
ios.FinishedLaunching((app, options) =>
{
Console.WriteLine("iOS: Application Finished Launching");
return true;
});
ios.OnResignActivation(app =>
{
Console.WriteLine("iOS: Application Resigned Activation");
});
ios.OnActivated(app =>
{
Console.WriteLine("iOS: Application Activated");
});
ios.WillTerminate(app =>
{
Console.WriteLine("iOS: Application Will Terminate");
});
});
#endif
});
return builder.Build();
}
}
}
ConfigureLifecycleEvents()
:
- ConfigureLifecycleEvents method is used to add the event handlers for the specific events of the platform.
Android-Specific Events:
OnCreate
: This is run once when the application is created i.e. when the application class is loaded.OnStart
: It is called when an application becomes the foreground application of the process.OnResume
: Called when the application is resumed, that is, when the application regains focus after being in the pause state.OnStop
: This is called when the application is not visible to the users, most of the time, it could be backgrounded.OnDestroy
: This event is called when the application is being destroyed.
iOS-Specific Events:
FinishedLaunching
: Triggered both on the application start-up completion and when its graphics become visible to a user.OnResignActivation
: Fired when the application is not longer running (for example when receiving the call).OnActivated
: This event is called when the application is brought to the foreground.WillTerminate
: Executed when the application is going to be terminated.
Platform Checks:
- the #if ANDROID and #if IOS directives guarantee it acts as a filter directing the code to adapt to only that specific platform which is being compiled.
R&O Platform specific events
To understand the actions of these lifecycle events, you should launch the application on both Android and iOS emulators and, preferably, devices.
Android Lifecycle Events:
- OnCreate: Occur at application start up.
- OnStart: Fired when the application is shown to the user Visible is scheduled to be invoked when app window is shown to the user.
- OnResume: Fired when the app regains focus.
- OnStop: Fired whenever the app is moved to the background.
- OnDestroy: Activated when the App is shutdown.
iOS Lifecycle Events:
- FinishedLaunching: Activated when the application is started and is set and running.
- OnResignActivation: Predefined to occur whenever the application is disrupted in some ways (for instance, by a phone call or by going to the background for a different application).
- OnActivated: Fired whenever app becomes active again.
- WillTerminate: Fired just before the application that launched the activity is about to be killed.
Real-World Scenarios for Using Lifecycle Events
Android:
- OnCreate: Load third party libraries or service.
- OnResume: Continue playing background music or update the data.
- OnStop: Preserving user data to be used when the app is no longer displayed on the screen.
iOS:
- FinishedLaunching: Initialize application level config and dependency.
- OnResignActivation: Stop active things like videos from continuing their performance throughout the time.
- WillTerminate: Leave important data and user preferences saved in order to be safe from any loss.
Summary of Platform Specific Lifecycle Events
Platform | Event | Description | Common Use Cases |
---|---|---|---|
Android | OnCreate | Called when the app is created. | Initialize libraries, setup services. |
Android | OnStart | Called when the app becomes visible. | Refresh UI, start services. |
Android | OnResume | Called when the app regains focus. | Restart paused animations or tasks. |
Android | OnStop | Called when the app goes into background. | Save state, pause resource-heavy activities. |
Android | OnDestroy | Called when the app is destroyed. | Clean up resources, release memory. |
iOS | FinishedLaunching | Called after app launch. | Set up dependencies, configure services. |
iOS | OnResignActivation | Called when the app is interrupted. | Pause ongoing activities, save transient data. |
iOS | OnActivated | Called when the app becomes active. | Resume paused activities, refresh the UI. |
iOS | WillTerminate | Called before the app is terminated. | Save data, perform clean-up operations. |