31 Days of Windows 8 | Day #29: Application Lifecycle

This article is Day #29 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample

Today, we’re going to talk about Application Lifecycle.  I wish there were a cooler word for this topic, but ultimately we’re looking at the management of the different states our application can be in on a user’s device.  Here’s an illustration (image from MSDN):

29-XAML-LifecycleDiagram

The reason that this is important to us as developers of Windows 8 applications is because we want to provide a seamless user experience in our apps.  When a user presses the Windows key on their machine, and leaves your app, you want to make sure you save or preserve their data in some way, so that when they come back, it’s all still there.

I Thought Windows Handled This Automatically??

Yes and no.  By default, if you run a Windows 8 application, leave it, and come back, it will automatically be exactly where you left it.  However, if you leave it, and then open 6 or 7 more applications, it’s likely that the operating system is going to suspend your application, or even terminate it.  Thankfully, there’s a couple of great mechanisms we can use to manage this.

Recognizing Your App Has Been Suspended

According to Microsoft, “an app can be suspended when the user switches away from it, or when Windows enters a low power state.  Most app stop running when the user switches away from them.”  There’s a few things you need to know about how your app will end up in a suspended state:

  • Your app “might” be suspended.  For the simple app I’ve built for this article, I’ve never seen it enter a suspended state on its own.
  • Generally, when the system runs out of resources, this is the time your app will enter a suspended state.
  • When you leave an app to use another, Windows will wait a few seconds before suspending it, just in case you were planning to return to it quickly.
  • If you need to execute any code before your application is suspended (we’ll talk about how next), you get a total of 5 seconds before your app is assumed to be unresponsive and terminated instead.  Keep this in mind…web service calls are probably not the thing to do.

So, if you’re anything like me, you’re probably wondering how we are going to write and test some code that only occurs when Windows feels like making it happen. Thankfully, there’s some tools for that.

First, let’s write some code.  On each page that a user might provide some input (whatever type of data), we can add an event handler that gets called when our app is suspended.  In the code below, I have created this event handler, and saved two values to local storage when it is called.

using System;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
 
namespace Day29_ApplicationLifecycle
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
 
        ApplicationDataContainer settings;
 
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Application.Current.Suspending += Current_Suspending;
            settings = ApplicationData.Current.LocalSettings;
        }
 
        void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {
            settings.Values["suspendedDateTime"] = DateTime.Now.ToString();
            settings.Values["customTextValue"] = CustomText.Text;
        }
 
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            Application.Current.Suspending += Current_Suspending;
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

You’ll notice, that like with all event handlers we create, I also remove it when the OnNavigatingFrom event is called.  We covered saving data on Day #8, so I won’t spend any time explaining that, other than to say that we are saving the time our app was suspended, as well as any text that was currently entered into a TextBox that I have on my MainPage.xaml page.  In order to verify this information has been saved, let’s add the Resuming event next.

Recognizing That Your App Is Resuming

In this case, we’re going to add a Resuming event, just like we did with the Suspending one.  When the method is called, I’m going to write the date and TextBox content back to the screen, so that the user can continue working on their data.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
 
namespace Day29_ApplicationLifecycle
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
 
        ApplicationDataContainer settings;
 
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Application.Current.Suspending += Current_Suspending;
            Application.Current.Resuming += Current_Resuming;
            settings = ApplicationData.Current.LocalSettings;
        }
 
        void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {
            settings.Values["suspendedDateTime"] = DateTime.Now.ToString();
            settings.Values["customTextValue"] = CustomText.Text;
        }
 
        void Current_Resuming(object sender, object e)
        {
            Message.Text = "Resumed.  Was suspended atnn" + settings.Values["suspendedDateTime"];
            CustomText.Text = settings.Values["customTextValue"].ToString();
        }
 
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            Application.Current.Resuming -= Current_Resuming;
            Application.Current.Suspending += Current_Suspending;
        }
 
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

How In The World Do I Test This Scenario?

Because this is a tough scenario to make happen automatically, there are tools inside Visual Studio that allow us to simulate these states in our application.  First, make sure that you’ve opened the Debug Location toolbar in Visual Studio.

29-XAML-DebugLocation

Once you’ve added that toolbar, it’s as simple as choosing one of these three options:

29-XAML-Suspend

  • Suspend will immediately put your application in a suspended state.  This will also fire your suspended event handler before it stops running.
  • Resume will obviously resume your app from a suspended state.  If your app is not suspended, nothing will happen.
  • Suspend and shutdown will simulate what happens when Windows terminates your application.  The suspended state will happen first, followed by a complete shutdown of your app.

If we use these buttons on the application we’ve created in this article, you’ll get an experience similar to the one in this short video:

 

In short, this is how we manage data on a page-by-page basis.  If you’re looking to do things at the overarching application level, you can take a look at your App.xaml.cs file.

Using App.xaml.cs to Manage the Lifecycle

There are already two methods sitting in your App.xaml.cs file, and you’ve already used them in previous days of this series.

  • OnLaunched is called when your application is launched normally.  This will not be called when your application is resumed, as the user will be taken directly to the page they were on previously.
  • OnSuspending is called AFTER your page event is called, but is also called when the application is suspended by Windows 8.  Saving any of your application-level data should be done here.

These methods provide you a little more power on a global level, but you’re still going to need to rely on your page level events for most of the state preservation you’re going to attempt.

Summary

In short, we want to provide a seamless experience for our users, so keep the lessons in this article in mind.  Don’t overdo it, though.  Saving unsaved data for a user is a convenience, so unless you think it will be important, don’t exhaust yourself trying to anticipate everything the user might need.

In games, if the user leaves, and they have to replay a level, so be it.  You don’t have to remember that they were jumping over that block to make it a great experience.  Remember which level they were on is probably enough.

If you would like to download the sample app that uses the code from this article, click the icon below:

downloadXAML

 

Tomorrow, we’re going to dive into the Windows Store, and give you all of the information you’re going to need to get your app available for sale.  See you then!

downloadTheTools

4 thoughts on “31 Days of Windows 8 | Day #29: Application Lifecycle

  1. You write, “You’ll notice, that like with all event handlers we create, I also remove it when the OnNavigatingFrom event is called.”

    But actually, you’re “+=”ing instead of “-=”ing there.

  2. Pingback: 31 Days of Windows 8 | Day #29: Application Lifecycle

  3. Where is day 30 and 31 articles.

  4. Pingback: 29# *31 dan Windows 8 aplikacija* www.jeffblankenburg.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s