Maui App Lifecycle
.NET (Microsoft)OfficialPublished by .NET (Microsoft)
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides essential patterns for handling the .NET MAUI application lifecycle. It details the four core app states, explains how to subscribe to cross-platform Window lifecycle events (Created, Activated, Deactivated, Stopped, Resumed, Destroying), and offers guidance on mapping these to platform-native callbacks. It includes best practices for state preservation during backgrounding and resume cycles, while highlighting critical differences between platform behaviors.
What it does
- Defines the four logical states of a .NET MAUI application.
- Provides patterns for subscribing to cross-platform Window lifecycle events.
- Maps cross-platform events to native Android, iOS, and Windows callbacks.
- Demonstrates how to use ConfigureLifecycleEvents for platform-specific hooks.
- Outlines best practices for saving and restoring state during backgrounding.
- Identifies common pitfalls like Android back-button behavior and multi-window event handling.
When to use it
- When you need to save or restore application state during backgrounding or resuming.
- When you need to execute logic upon window activation or deactivation.
- When you need to hook into platform-specific native lifecycle callbacks.
- When you need to distinguish between app visibility states like Deactivated and Stopped.
Advantages
- Ensures consistent state management across different operating systems.
- Helps prevent common issues like data loss during unexpected app termination.
- Provides clear guidance on multi-window lifecycle behavior.
- Reduces reliance on legacy Xamarin.Forms methods in favor of modern .NET MAUI patterns.
Usage examples
- “How do I save user input when the app is backgrounded?”
- The skill provides a workflow to use OnStopped and OnDestroying to save data to Preferences, ensuring state is captured even if the app is terminated.
- “How can I run code when my Android app resumes?”
- The skill explains how to use the Resumed event or ConfigureLifecycleEvents to trigger logic specifically when the app returns to the foreground.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/dotnet/maui-app-lifecycle/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip maui-app-lifecycle.zip -d .agents/skills
Documentation by .NET (Microsoft)
.NET MAUI App Lifecycle
Handle application state transitions correctly in .NET MAUI. This skill covers the cross-platform Window lifecycle events, their platform-native mappings, and patterns for preserving state across backgrounding and resume cycles.
When to Use
Saving or restoring state when the app backgrounds or resumes
Subscribing to Window lifecycle events (Created, Activated, Deactivated, Stopped, Resumed, Destroying)
Hooking into platform-native lifecycle callbacks via
ConfigureLifecycleEventsDeciding where to place initialization, teardown, or refresh logic
Understanding the difference between Deactivated and Stopped
When Not to Use
Page-level navigation events — use Shell navigation guidance instead
Registering services at startup — use dependency injection guidance instead
Calling platform-specific APIs outside lifecycle context — use platform invoke guidance instead
Inputs
The target lifecycle transition (e.g., "save draft when backgrounded", "refresh data on resume")
Which platforms the developer targets (Android, iOS, Mac Catalyst, Windows)
Whether the app uses multiple windows (iPad, Mac Catalyst, desktop Windows)
App States
A .NET MAUI app moves through four states:
| State | Description |
|---|---|
| Not Running | Process does not exist |
| Running | Foreground, receiving input |
| Deactivated | Visible but lost focus (dialog, split-screen, notification shade) |
| Stopped | Fully backgrounded, UI not visible |
Typical flow: Not Running → Running → Deactivated → Stopped → Running (resumed) or Not Running (terminated).
Window Lifecycle Events
Microsoft.Maui.Controls.Window exposes six cross-platform events:
| Event | Fires when |
|---|---|
Created | Native window allocated |
Activated | Window receives input focus |
Deactivated | Window loses focus (may still be visible) |
Stopped | Window is no longer visible |
Resumed | Window returns to foreground after Stopped |
Destroying | Native window is being torn down |
Subscribing via CreateWindow
Override CreateWindow in your App class and attach event handlers:
public partial class App : Application
{
protected override Window CreateWindow(IActivationState? activationState)
{
var window = base.CreateWindow(activationState);
window.Created += (s, e) => Debug.WriteLine("Created");
window.Activated += (s, e) => Debug.WriteLine("Activated");
window.Deactivated += (s, e) => Debug.WriteLine("Deactivated");
window.Stopped += (s, e) => Debug.WriteLine("Stopped");
window.Resumed += (s, e) => Debug.WriteLine("Resumed");
window.Destroying += (s, e) => Debug.WriteLine("Destroying");
return window;
}
}Subscribing via a Custom Window Subclass
Create a Window subclass and override the virtual methods:
public class AppWindow : Window
{
public AppWindow(Page page) : base(page) { }
protected override void OnActivated() { /* refresh UI */ }
protected override void OnStopped() { /* save state */ }
protected override void OnResumed() { /* restore state */ }
protected override void OnDestroying() { /* cleanup */ }
}Return it from CreateWindow:
protected override Window CreateWindow(IActivationState? activationState)
=> new AppWindow(new AppShell());Workflow: Save and Restore State on Background
Identify transient state — draft text, scroll position, form inputs, timer values.
Save in
OnStopped— usePreferencesfor small values or file serialization for larger state.Restore in
OnResumed— read back saved values and apply to your view model.Also save in
OnDestroyingon Android — the back button can skipStoppedentirely.Keep handlers fast — complete within 1–2 seconds to avoid ANR on Android or watchdog kills on iOS.
protected override void OnStopped()
{
base.OnStopped();
Preferences.Set("draft_text", _viewModel.DraftText);
Preferences.Set("scroll_y", _viewModel.ScrollY);
}
protected override void OnResumed()
{
base.OnResumed();
_viewModel.DraftText = Preferences.Get("draft_text", string.Empty);
_viewModel.ScrollY = Preferences.Get("scroll_y", 0.0);
}
protected override void OnDestroying()
{
base.OnDestroying();
// Android back-button can skip Stopped
Preferences.Set("draft_text", _viewModel.DraftText);
}Platform Lifecycle Mapping
Android
| Window Event | Android Callback |
|---|---|
| Created | OnCreate |
| Activated | OnResume |
| Deactivated | OnPause |
| Stopped | OnStop |
| Resumed | OnRestart → OnStart → OnResume |
| Destroying | OnDestroy |
iOS / Mac Catalyst
| Window Event | UIKit Callback | AddiOS builder method |
|---|---|---|
| Created | WillFinishLaunching / SceneWillConnect | .WillFinishLaunching() / .SceneWillConnect() |
| Activated | DidBecomeActive | .OnActivated() |
| Deactivated | WillResignActive | .OnResignActivation() |
| Stopped | DidEnterBackground | .DidEnterBackground() |
| Resumed | WillEnterForeground | .WillEnterForeground() |
| Destroying | WillTerminate | .WillTerminate() |
⚠️ The UIKit selector names and the
AddiOSbuilder method names differ for activation. There is no.DidBecomeActive()or.WillResignActive()builder method — use.OnActivated()and.OnResignActivation()or the code will not compile.
Windows (WinUI)
| Window Event | WinUI Callback |
|---|---|
| Created | OnLaunched |
| Activated | Activated (foreground) |
| Deactivated | Activated (background) |
| Stopped | VisibilityChanged (false) |
| Resumed | VisibilityChanged (true) |
| Destroying | Closed |
Hooking Native Lifecycle Directly
Use ConfigureLifecycleEvents in MauiProgram.cs when you need platform-specific callbacks beyond what Window events provide:
builder.ConfigureLifecycleEvents(events =>
{
#if ANDROID
events.AddAndroid(android => android
.OnCreate((activity, bundle) => Debug.WriteLine("Android OnCreate"))
.OnResume(activity => Debug.WriteLine("Android OnResume"))
.OnPause(activity => Debug.WriteLine("Android OnPause"))
.OnStop(activity => Debug.WriteLine("Android OnStop"))
.OnDestroy(activity => Debug.WriteLine("Android OnDestroy")));
#elif IOS || MACCATALYST
events.AddiOS(ios => ios
.OnActivated(app => Debug.WriteLine("iOS OnActivated"))
.OnResignActivation(app => Debug.WriteLine("iOS OnResignActivation"))
.DidEnterBackground(app => Debug.WriteLine("iOS DidEnterBackground"))
.WillEnterForeground(app => Debug.WriteLine("iOS WillEnterForeground")));
#elif WINDOWS
events.AddWindows(windows => windows
.OnLaunched((app, args) => Debug.WriteLine("Windows OnLaunched"))
.OnActivated((window, args) => Debug.WriteLine("Windows Activated"))
.OnClosed((window, args) => Debug.WriteLine("Windows Closed")));
#endif
});Common Pitfalls
Resumed does not fire on first launch. The initial sequence is
Created→Activated. UseOnActivatedfor logic that must run on every foreground entry, notOnResumed.Deactivated ≠ Stopped. A dialog, split-screen, or notification pull-down triggers
DeactivatedwithoutStopped. Do not perform heavy saves inOnDeactivated— the app may never actually background.Android back button skips Stopped. On Android, pressing back may call
Destroyingdirectly withoutStopped. Place critical save logic in bothOnStoppedandOnDestroying.Multi-window apps fire events independently. On iPad, Mac Catalyst, and desktop Windows each
Windowinstance fires its own lifecycle events. Do not assume a single global lifecycle.Long-running handlers cause kills. Android enforces a ~5 second ANR timeout; iOS has limited background execution time. Keep lifecycle handlers synchronous and fast — use
Preferencesfor quick saves, not database writes.Do not use legacy Xamarin.Forms lifecycle methods.
Application.OnStart(),Application.OnSleep(), andApplication.OnResume()exist for backward compatibility but bypass Window-level events. In .NET MAUI, preferWindowlifecycle events (OnActivated,OnStopped,OnResumed, etc.) for correct multi-window behavior.
Files
- ATTRIBUTION.mdAdded by AutoGineer847 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md9.0 KiB
- references/lifecycle-api.md5.5 KiB
LICENSE
The MIT License (MIT) Copyright (c) .NET Foundation and Contributors All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- .NET (Microsoft)
- Publisher
- .NET (Microsoft) (Official)
- Source
- dotnet/skills · plugins/dotnet-maui/skills/maui-app-lifecycle · commit 96c3d68
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by .NET (Microsoft).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download maui-app-lifecycle.zip