Xamarin.Forms App Lifecycle Tutorial
Before attempting this tutorial, you should have successfully completed the:
- Build your first Xamarin.Forms app quickstart.
- StackLayout tutorial.
- Entry tutorial.
In this tutorial, you learn how to:
- Respond to an application starting, sleeping, or resuming.
- Persist data across lifecycle state changes.
You will use Visual Studio 2019, or Visual Studio for Mac, to create a simple application that demonstrates how to persist data across lifecycle state changes. The following screenshots show the final application:
Respond to lifecycle state changes
To complete this tutorial you should have Visual Studio 2019 (latest release), with the Mobile development with .NET workload installed. In addition, you will require a paired Mac to build the tutorial application on iOS. For information about installing the Xamarin platform, see Installing Xamarin. For information about connecting Visual Studio 2019 to a Mac build host, see Pair to Mac for Xamarin.iOS development.
Launch Visual Studio, and create a new blank Xamarin.Forms app named AppLifecycleTutorial.
Important
The C# and XAML snippets in this tutorial requires that the solution is named AppLifecycleTutorial. Using a different name will result in build errors when you copy code from this tutorial into the solution.
For more information about the .NET Standard library that gets created, see Anatomy of a Xamarin.Forms application in the Xamarin.Forms Quickstart Deep Dive.
In Solution Explorer, in the AppLifecycleTutorial project, expand App.xaml and double-click App.xaml.cs to open it. Then, in App.xaml.cs, update the
OnStart,OnSleep, andOnResumeoverrides as follows:protected override void OnStart() { Console.WriteLine("OnStart"); } protected override void OnSleep() { Console.WriteLine("OnSleep"); } protected override void OnResume() { Console.WriteLine("OnResume"); }This code updates the application lifecycle method overrides, with
Console.WriteLinestatements that indicate when each method has been invoked:- The
OnStartmethod is invoked when the application starts. - The
OnSleepmethod is invoked when the application goes to the background. - The
OnResumemethod is invoked when the application resumes from the background.
Note
There is no method for application termination. Under normal circumstances, application termination will occur from the
OnSleepmethod.- The
In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote iOS simulator or Android emulator. When the application starts, the
OnStartmethod is invoked, and OnStart is output to the Visual Studio Output window:[Mono] Found as 'java_interop_jnienv_get_object_array_element'. OnStart [OpenGLRenderer] HWUI GL PipelineWhen the application is backgrounded (by tapping the Home button on iOS or Android), the
OnSleepmethod is invoked:[EGL_emulation] eglMakeCurrent: 0x83ee2920: ver 3 0 (tinfo 0x8357eff0) OnSleep [Mono] Image addref System.Runtime.Serialization[0x83ee19c0] -> System.Runtime.Serialization.dll[0x83f57b00]: 2Then, when the application resumes from the background (tap the application icon on iOS, tap the Overview button on Android and select the AppLifecycleTutorial application), the
OnResumemethod is invoked:Thread finished: <Thread Pool> #5 OnResume [EGL_emulation] eglMakeCurrent: 0x83ee2920: ver 3 0 (tinfo 0x8357eff0)Note
These code blocks show example output when running the application on Android.
In Visual Studio, stop the application.
For more information about the Xamarin.Forms app lifecycle, see Xamarin.Forms App Lifecycle.
Persist data across lifecycle state changes
The Application subclass has a static Properties dictionary that can be used to store data across lifecycle state changes. This dictionary uses a string key and stores an object value. The dictionary is saved to the device automatically, and is repopulated when the application is restarted.
Important
The Properties dictionary can only serialize primitive types for storage.
In this exercise, you'll modify the application to persist the text from an Entry upon backgrounding, and restore the text to the Entry when the application is restarted.
In Solution Explorer, in the AppLifecycleTutorial project, expand App.xaml and double-click App.xaml.cs to open it. Then, in App.xaml.cs, remove all of the template code and replace it with the following code:
using System; using Xamarin.Forms; namespace AppLifecycleTutorial { public partial class App : Application { const string displayText = "displayText"; public string DisplayText { get; set; } public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { Console.WriteLine("OnStart"); if (Properties.ContainsKey(displayText)) { DisplayText = (string)Properties[displayText]; } } protected override void OnSleep() { Console.WriteLine("OnSleep"); Properties[displayText] = DisplayText; } protected override void OnResume() { Console.WriteLine("OnResume"); } } }This code defines a
DisplayTextproperty, and adisplayTextconstant. When the application is backgrounded, or terminated, theOnSleepmethod override adds theDisplayTextproperty value to thePropertiesdictionary, against a key ofdisplayText. Then when the application starts, provided that thePropertiesdictionary contains thedisplayTextkey, the value for the key is restored to theDisplayTextproperty.Important
Always check the
Propertiesdictionary for the presence of a key before accessing it, to prevent unexpected errors.It's not necessary to restore data from the
Propertiesdictionary in theOnResumemethod overload. This is because when an application is backgrounded, it and its state is still in memory.In Solution Explorer, in the AppLifecycleTutorial project, double-click MainPage.xaml to open it. Then, in MainPage.xaml, remove all of the template code and replace it with the following code:
<?xml version="1.0" encoding="utf-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="AppLifecycleTutorial.MainPage"> <StackLayout Margin="20,35,20,20"> <Entry x:Name="entry" Placeholder="Enter text here" Completed="OnEntryCompleted" /> </StackLayout> </ContentPage>This code declaratively defines the user interface for the page, which consists of an
Entryin aStackLayout. TheEntry.Placeholderproperty specifies the placeholder text that's shown when theEntryis first displayed, and an event handler namedOnEntryCompletedis registered with theCompletedevent. In addition, theEntryhas a name specified with thex:Nameattribute. This enables the code-behind file to access theEntryobject using the name assigned to it.In Solution Explorer, in the AppLifecycleTutorial project, expand MainPage.xaml and double-click MainPage.xaml.cs to open it. Then, in MainPage.xaml.cs, add an override for the
OnAppearingmethod, and theOnEntryCompletedevent handler to the class:protected override void OnAppearing() { base.OnAppearing(); entry.Text = (Application.Current as App).DisplayText; } void OnEntryCompleted(object sender, EventArgs e) { (Application.Current as App).DisplayText = entry.Text; }The
OnAppearingmethod retrieves the value of theApp.DisplayTextproperty and sets it as theTextproperty value of theEntry.Note
The
OnAppearingmethod override is executed after theContentPageis laid out, but just before it becomes visible. Therefore, this is a good place to set the content of Xamarin.Forms views.When text is finalized in the
Entry, with the return key, theOnEntryCompletedmethod executes and theEntrytext is stored in theApp.DisplayTextproperty.In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote iOS simulator or Android emulator.
Enter some text into the
Entryand hit the return key. Then, background the application by tapping the Home button to invoke theOnSleepmethod.In Visual Studio, stop the application and relaunch it again, and the text that was previously entered into the
Entrywill be restored:In Visual Studio, stop the application.
For more information about persisting data to the properties dictionary, see Properties Dictionary in the Xamarin.Forms App Class guide.
Congratulations!
Congratulations on completing this tutorial, where you learned how to:
- Respond to an application starting, sleeping, or resuming.
- Persist data across lifecycle state changes.
Next steps
To learn more about the basics of creating mobile applications with Xamarin.Forms, continue to the Local Database tutorial.
Related links
Have an issue with this section? If so, please give us some feedback so we can improve this section.
