left-icon

Xamarin.Forms for macOS Succinctly®
by Alessandro Del Sole

Previous
Chapter

of
A
A
A

CHAPTER 9

Managing the App Lifecycle

Managing the App Lifecycle


The application lifecycle involves events such as startup, suspension, and resume. Every platform manages the application lifecycle differently, so implementing platform-specific code in iOS and Android projects would require some effort. Luckily, Xamarin.Forms allows you to manage the app lifecycle in a unified way, and takes care of performing the platform-specific work on your behalf. This chapter provides a quick explanation of the app lifecycle and how you can easily manage your app’s behavior.

Introducing the App class

The App class is a singleton class that inherits from Application and is defined inside the App.xaml.cs file. It can be thought of as an object that represents your application running, and includes the necessary infrastructure to handle resources, navigation, and the application lifecycle. If you need to store some data into variables that should be available to all pages in the application, you can expose static fields and properties in the App class. At a higher level, the App class exposes some fundamental members that you might need across the whole app lifecycle: the MainPage property, which you assign with the root page of your application, and the OnStart, OnSleep, and OnResume methods, which you use to manage the application lifecycle described in the next section.

Managing the app lifecycle

The application lifecycle can be summarized in four events: startup, suspension, resume, and shutdown. The Android and iOS platforms manage these events differently, but Xamarin.Forms provides a unified system that allows for managing an app’s startup, suspension, and resume events from a single, shared C# codebase. These events are represented by the OnStart, OnSleep, and OnResume methods that you can see in the App.xaml.cs file, whose body is empty.

Currently, no specific method handles the app shutdown, because in most cases handling suspension is sufficient. For instance, you might load some app settings within OnStart at startup, save settings when the app is suspended within OnSleep, and reload settings when the app comes back to the foreground within OnResume. For a better understanding of this example, you can install the Settings plugin from NuGet to all the projects in the solution.

Tip: Full guidance on the Settings plugin is available on its GitHub page.

In the Helpers\Settings.cs file, replace the auto-generated code with the content of Code Listing 34, which implements a setting of type DateTime that you can use to get and set the date and time for app lifecycle events.

Code Listing 34

using Plugin.Settings;

using Plugin.Settings.Abstractions;

using System;

 

namespace App1.Helpers

{

     public static class Settings

     {

          private static ISettings AppSettings

          {

               get

               {

                    return CrossSettings.Current;

               }

          }

        private const string AccessDateSettings = "access_date";

        private static readonly DateTime AccessDateDefault = DateTime.Now;

 

        public static DateTime AccessDate

        {

            get

            {

                return AppSettings.GetValueOrDefault(AccessDateSettings, 

                       AccessDateDefault);

            }

            set

            {

                AppSettings.AddOrUpdateValue(AccessDateSettings, value);

            }

        }

    }

}

using Plugin.Settings;

using Plugin.Settings.Abstractions;

using System;

 

namespace App1.Helpers

{

     public static class Settings

     {

          private static ISettings AppSettings

          {

               get

               {

                    return CrossSettings.Current;

               }

          }

        private const string AccessDateSettings = "access_date";

        private static readonly DateTime AccessDateDefault = DateTime.Now;

 

        public static DateTime AccessDate

        {

            get

            {

                return AppSettings.GetValueOrDefault(AccessDateSettings, 

                      AccessDateDefault);

            }

            set

            {

                AppSettings.AddOrUpdateValue(AccessDateSettings, value);

            }

        }

    }

}

As you can see in Code Listing 35, you can now get and set the setting’s value according to the app lifecycle event. In this case, storing the access date makes sense when the app starts or resumes, not when it is suspended (in which case you might want to add a specific setting).

Code Listing 35

using App1.Helpers;

using System;

 

using Xamarin.Forms;

 

namespace App1

{

    public partial class App : Application

    {

        public App()

        {

            InitializeComponent();

 

            MainPage = new App1.MainPage();

        }

 

        protected override void OnStart()

        {

            // Handle when your app starts.

            Settings.AccessDate = DateTime.Now;

        }

        protected override void OnResume()

        {

            // Handle when your app resumes.

            Settings.AccessDate = DateTime.Now;

        }

 

        protected override void OnSleep()

        {

            // Handle when your app sleeps.

 

            // Add a new setting to store the date/time for OnSleep.

        }

    }

}

With the help of breakpoints and the debugger, you will be able to demonstrate that the application enters the appropriate methods according to the lifecycle event.

Sending and receiving messages

Xamarin.Forms includes an interesting static class called MessagingCenter. This class can send broadcast messages that subscribers can receive and take actions, based on a publisher/subscriber model. In its most basic form, you use the MessagingCenter to send a message as follows:

MessagingCenter.Send<MainPage>(this, "MESSAGE");

The Send method’s type parameters specify the types subscribers should expect; its arguments are the sender (MainPage in this case), and the message in the form of a string. You can specify multiple type parameters, and therefore, multiple arguments before the message.

Tip: The compiler is able to infer type parameters for Send, so it is not mandatory to specify them explicitly.

Subscribers can then listen for messages and take actions as follows:

MessagingCenter.Subscribe<MainPage>

    (this, "MESSAGE", (sender) => 

    {

        // Do something here

    });

When MessagingCenter.Send is invoked somewhere, objects listening for a particular message will execute the action specified within Subscribe (this does not have to necessarily be a lambda expression—it can be an expanded delegate). When their jobs are finished, subscribers can invoke MessagingCenter.Unsubscribe to stop listening to a message, passing the sender as the type parameter, the current object, and the message, as follows:

MessagingCenter.Unsubscribe<MainPage>(this, "MESSAGE");

The MessagingCenter class can be very useful when you have program control flows that are decoupled from the user interface, and can even be useful with MVVM implementations.

Chapter summary

Managing the application lifecycle can be very important, especially when you need to get and store data at the application startup or suspension. Xamarin.Forms avoids the need to write platform-specific code and offers a cross-platform solution through the OnStart, OnSleep, and OnResume methods that allow handling the startup, suspension, and resume events, respectively, from a single C# codebase—regardless of the platform the app is running on. Not only is this a powerful feature, but it really simplifies your work as a developer.

Finally, you have seen in this chapter the MessagingCenter class, a static object that allows for sending and subscribing messages, and is useful with logics decoupled from the user interface.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.