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
, andOnResume
overrides 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.WriteLine
statements that indicate when each method has been invoked:- The
OnStart
method is invoked when the application starts. - The
OnSleep
method is invoked when the application goes to the background. - The
OnResume
method 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
OnSleep
method.- 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
OnStart
method 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 Pipeline
When the application is backgrounded (by tapping the Home button on iOS or Android), the
OnSleep
method is invoked:[EGL_emulation] eglMakeCurrent: 0x83ee2920: ver 3 0 (tinfo 0x8357eff0) OnSleep [Mono] Image addref System.Runtime.Serialization[0x83ee19c0] -> System.Runtime.Serialization.dll[0x83f57b00]: 2
Then, 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
OnResume
method 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
DisplayText
property, and adisplayText
constant. When the application is backgrounded, or terminated, theOnSleep
method override adds theDisplayText
property value to theProperties
dictionary, against a key ofdisplayText
. Then when the application starts, provided that theProperties
dictionary contains thedisplayText
key, the value for the key is restored to theDisplayText
property.Important
Always check the
Properties
dictionary for the presence of a key before accessing it, to prevent unexpected errors.It's not necessary to restore data from the
Properties
dictionary in theOnResume
method 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
Entry
in aStackLayout
. TheEntry.Placeholder
property specifies the placeholder text that's shown when theEntry
is first displayed, and an event handler namedOnEntryCompleted
is registered with theCompleted
event. In addition, theEntry
has a name specified with thex:Name
attribute. This enables the code-behind file to access theEntry
object 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
OnAppearing
method, and theOnEntryCompleted
event 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
OnAppearing
method retrieves the value of theApp.DisplayText
property and sets it as theText
property value of theEntry
.Note
The
OnAppearing
method override is executed after theContentPage
is 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, theOnEntryCompleted
method executes and theEntry
text is stored in theApp.DisplayText
property.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
Entry
and hit the return key. Then, background the application by tapping the Home button to invoke theOnSleep
method.In Visual Studio, stop the application and relaunch it again, and the text that was previously entered into the
Entry
will 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.