• Home
  • Documentation
Show / Hide Table of Contents
  • Introduction
  • Commands
    • Commanding
    • Composite Commands
    • Async Commands
    • Error Handling
  • Dependency Injection
    • Getting Started
    • Registering Types
    • Microsoft Extensions (Supplement)
    • Platform Specific Services
    • Exception Handling
    • ContainerLocator
    • Appendix
  • Dialog Service
    • Dialog Service
    • IDialogAware ViewModels
    • IDialogWindow (WPF & Uno Platform)
  • Event Aggregator
  • Mvvm
    • BindableBase
    • ViewModelLocator
  • Modularity
    • Getting Started
    • Module Catalog
    • Module Initialization
  • Navigation
    • Getting Started
    • INavigationParameters
    • Page Navigation
    • Regions
      • Getting Started
      • Region Manager
      • Region Adapters
      • Region Behaviors
      • About Navigation in Prism
      • Basic Region Navigation
      • View/ViewModel Participation
      • Navigating to Existing Views
      • Passing Parameters
      • Confirming Navigation
      • Controlling View Lifetime
      • Navigation Journal
  • Platforms
    • Maui
      • Getting Started
      • Migrating from Prism.Forms
      • PrismAppBuilder
      • AppModel
        • IPageLifecycleAware
      • Behaviors
        • Introduction
        • BehaviorBase<T>
        • EventToCommandBehavior
        • PageBehaviorFactory
      • Dialogs
        • Getting Started
        • IPageDialogService
      • Navigation
        • Introduction
        • Page Navigation
        • NavigationBuilder
        • TabbedPages
        • Understanding the INavigationResult
        • NavigationExceptions
        • Global Navigation Observer
        • XAML Navigation
    • Uno Platform
      • Getting Started
      • Uno.Extensions
    • Wpf
      • Introduction
      • Getting Started
      • View Composition
      • Interactivity
        • Event To Command
    • Xamarin.Forms
      • Create Your First App
      • Behaviors
        • Working with Behaviors
        • EventToCommand Behavior
        • PageBehaviorFactory
      • Dialogs
        • Dialogs
        • Page Dialog Service
        • Dialog Service
        • Styling Dialogs
      • Navigation
        • Navigation Basics
        • Passing Parameters
        • Confirming Navigation
        • Deep Linking
        • Working w/ MasterDetailPages
        • Working w/ NavigationPages
        • Working w/ TabbedPages
        • XAML Navigation
      • Application Lifecycle
      • Page Lifecycle
      • Additional Platforms
        • GTK
  • Magician
    • Getting Started
  • Plugins
    • Essentials
      • Getting Started
      • ApplicationModel
        • App Context
        • Browser
        • Communication
          • Email
          • Phone Dialer
        • Data Transfer
          • Clipboard
          • Share
        • LatestVersion
        • Launcher
        • Version Tracking
      • Devices
        • Battery
        • Sensors
          • Biometrics
          • Geocoding
          • Geofencing
          • Geolocation
      • IO
        • File System
        • Stores
      • Media
        • Getting Started
        • Camera
        • Video
      • Networking
        • Connectivity
      • Notifications
        • Getting Started
        • ActionSheets
        • Alerts
        • Prompts
      • Permissions
        • Permissions Manager
      • Threading
        • Main Thread
    • Logging
      • Getting Started
      • Interop
        • Essentials
        • Microsoft Extensions
      • Providers
        • AppCenter
        • Console
        • Debug
        • Firebase
        • Graylog
        • Kochava
        • Raygun
        • Sentry
        • Unit Testing
        • Xunit
    • Observable Regions
    • Popups
  • Pipelines
    • Commercial Plus

Application Lifecycle Management

Mobile applications development has to deal with the concept of application lifecycle. With this we mean that mobile apps are created to manage scenarios where battery life, CPU and memory are limited (as opposed to the classic desktop app where all of this is unlimited).

When a mobile app is running in backgroud it is suspended by the OS after a few seconds. The exact timing is different from OS to OS and other factors. When the application is suspended it is frozen: the app will continue to use memory but all the running operations are stopped. This way, every other application can make use of resources. However RAM isn't infinite and the app will be killed by the OS to free some memory if necessary.

As mobile developers you need to take care of this to provide your users a smooth and transparent experience whenever possible and restore the previous state of the app.

The typical application lifecycle events are:

  • Initializing. This happens the first time the app is launched.
  • Resuming. This happens every time we restore the app from the background after it has been suspended.
  • Sleeping. This happens when the OS decides to freeze our app after it has gone in background.

The management of these events can be tricky in an MVVM app but Prism provides the IApplicationLifecycleAware interface to make your life easier.

How to handle ALM in your ViewModels

The first thing you have to do to is to implement the IApplicationLifecycleAware interface in your ViewModel class. Implemening this interface means that you have to provide an implementation of the OnResume() and OnSleep() method that are called by the framework when the app is resuming and going to sleep respectively. The typical operation you'll do in the OnSleep() method is to save the state of your ViewModel to later restore it during the execution of the OnResume() method.

The following is an example of a ViewModel that implements IApplicationLifecycleAware.

public class ViewModelExample : ViewModelBase, IApplicationLifecycleAware
{
    protected INavigationService NavigationService { get; }

    public ViewModelExample(INavigationService navigationService)
    {
        NavigationService = navigationService;
    }

    public void OnResume()
    {
        //Restore the state of your ViewModel.
    }

    public  void OnSleep()
    {
        //Save the state of your ViewModel.
    }
}

How to handle ALM at Application level

You can handle ALM events at the Application level by overriding the OnSleep() and OnResume() methods in the App class. The following is an example of an App class with ALM management.

public partial class App : PrismApplication
{

    public App() : this(null) { }

    public App(IPlatformInitializer initializer) : base(initializer) { }

    protected override async void OnInitialized()
    {
        InitializeComponent();

        var result = await NavigationService.NavigateAsync("NavigationPage/MainPage");
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation<NavigationPage>();
        containerRegistry.RegisterForNavigation<MainPage>();
    }

    protected override void OnResume()
    {
        base.OnResume();

        // TODO: Refresh network data, perform UI updates, and reacquire resources like cameras, I/O devices, etc.
    }

    protected override void OnSleep()
    {
        base.OnSleep();

        // TODO: This is the time to save app data in case the process is terminated.
        // This is the perfect timing to release exclusive resources (camera, I/O devices, etc...)
    }
}

Handling app resume and suspend

In general, an application goes into sleep mode when it no longer commands the screen and has become inactive. From this sleep mode, an application can be resumed (signaled by an OnResume() call) or terminated. But this is important: after the OnSleep() call, there is no further notification that an application is being terminated. The OnSleep() call is as close as you get to a termination notification, and it always precedes a termination. For example, if your application is running and the user turns off the phone, the application gets an OnSleep() call as the phone is shutting down. If your program has established a connection with a web service, or is in the process of establishing such a connection, you might want to use OnResume() to restore that connection. Perhaps the connection has timed out in the interval that the program was inactive. Or perhaps some fresh data is available.

Debugging tips and tricks

When your app is attached to the Visual Studio debugger, it will not be suspended. You can suspend it from the debugger, however, and then send it a Resume event so that you can debug your code. Make sure the Debug Location toolbar is visible and click the drop-down next to the Suspend icon. Then choose Resume.

how to activate debug-location

Reference

  • Xamarin Docs App Lifecycle

  • Xamarin Forms Book

  • PrismApplicationBase source code

  • Edit on GitHub
  • Ask questions
  • Follow @PrismLib
  • Follow @BrianLagunas
  • Follow @DanJSiegel
Back to top Copyright 2015-2024 Prism Software, LLC