App Hub

Visuals & Media

Make your applications visually appealing with images, animations, and media.

Sensors & Other Phone Specific Features

Use unique features of the phone, such the accelerometer, GPS, and camera, in your applications.

Running your App in the Background (Tombstoning)
Silverlight quickstart for Windows Phone development

The Windows Phone operating system allows only one application to run at a time. When the user navigates away from the application, the operating system terminates the application. To provide a seamless experience to the user, the operating system provides support to help you restore your application to a presentable state when it's reactivated. This QuickStart describes the tombstoning process, the application lifecycle, and how to restore state.

This QuickStart contains the following sections:

 

Tombstoning Overview

The Windows Phone operating system doesn't allow any third-party applications to run in the background; therefore, only one application can run at a time. The reasons for not allowing any third-party applications to run in the background are to preserve battery life and to ensure a consistent and responsive user experience. When the user navigates away from the application, the Windows Phone operating system deactivates the application. This is called tombstoning. It's the process in which the operating system deactivates an application's process when the user navigates away from the application. An application can get deactivated in the following cases:

  • A phone call is received. Reactivation occurs when the phone call ends.
  • The phone goes to sleep. Reactivation occurs when the user wakes the phone.
  • The user presses the Start or Search button, or responds to a notification. Reactivation occurs when the user returns to the application by pressing the Back button one or more times.
  • The application invokes an external task. Reactivation occurs when the user completes the task.

When the tombstoned application is activated again, it must look the same as it looked before tombstoning in order to maintain a seamless user experience. Ideally, the user shouldn't know that it's a completely new process when he reactivates a tombstoned application. For example, suppose you open an application with a long page, and you've scrolled down a bit to read the page, then you navigate to another page. When you go back to the original page, it's not too upsetting if you've lost your place and you're back at the top of the page. On the other hand, if you've just spent minutes filling out a large form, you definitely don't want to see all your work gone after another page tells you that you've made one tiny error.

To achieve this, when the application gets deactivated, the operating system maintains some state information about the application in memory and uses that information to restore your application to a presentable state when it's reactivated.

Windows Phone provides methods and events to store and restore application and page states. These methods and events are described later in this QuickStart.

 

Application Life Cycle

Since Window Phone applications can be tombstoned, they have a unique life cycle that you need to understand. The operating system provides four events that indicate the state of your application in the life cycle. You can use these events to take appropriate action in your application. These events are Launching, Closing, Deactivated, and Activated. The following illustration shows when these events occur.

Application Life Cycle

Launching

When an application is started from the Start screen, it is said to be launched. Whenever the user launches an application, a new instance of the application is created. When the application is started, a Launching event is raised. The following code shows the Launching event that is present in App.xaml.cs file.

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}

You can use the Launching event to incrementally save settings and other persisted data to reduce the amount of data that needs to be saved when the application's state changes. This is optional, and for applications with a small amount of persisted data, may be unnecessary.

Closing

By pressing the hardware Back button, the navigation model allows the user to "step back," or navigate backwards through the application pages, and even across applications. However, once the user reaches the application's first page, pressing the Back button again raises the Closing event and terminates your application. You can use this event to save persistent data to isolated storage. The following code shows the Closing event that is present in App.xaml.cs file.

// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}

Deativated

An application could be deactivated (not closed) either as a result of another application taking control of the foreground, such as an incoming phone call, or as a result of the user pressing the Start button. In such cases, the Deactivated event is raised. The following code shows the Deactivated event that is present in App.xaml.cs file.

// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}

Unlike an application that is closed, a deactivated application may become tombstoned. This means that it is no longer running, but the operating system keeps a record of the application and stores a set of state data for the application. It's possible that the user will return to a tombstoned application, at which point it will be reactivated. So, you should store information about the application's current state by using the dictionary that is exposed through the PhoneApplicationService.State property in the Deactivated event handler. The data stored in this dictionary are transient state data, that is, data that will help the application reestablish the state of the application before it was deactivated. Because there is no guarantee that a tombstoned application will ever be reactivated, you should also save the application's persistent data to isolated storage during this event. All of the actions taken in the Deactivated event handler must be completed within 10 seconds or the operating system will terminate the application. So if your application has large quantities of persisted data, you may want to save incrementally as the application is running.

It's also possible for an application to be deactivated without being tombstoned. For example, if the user presses the Start button and then the Back button in rapid succession. For this reason, it's important not to do anything destructive in the Deactivated event handler. Your application should be able to continue after completing the Deactivated event handler without the Activated handler being called.

Activated

After an application has been deactivated and tombstoned, the user can return to the application by pressesing the Back button until the application is reached. When the user returns to a tombstoned application, it is reactivated and the Activated event is raised. You can use this event to read values from the PhoneApplicationService.State to retrieve the state of the application that the user experienced before the application was deactivated. The following code shows the Activated event that is present in App.xaml.cs file

// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
 

Application State

Application state is the state of the application that isn't specific to a particular page. If your application uses global data such as login information or application settings like themes, it's likely that they'll be used by multiple pages within the application. This data is considered to be a part of application state. When your application gets reactivated after being tombstoned, the data are lost unless you specifically save the date. In general you use the Launching, Closing, Deactivated and Activated events to initialize and maintain application state. When your application is tombstoned, the operating system saves the contents of the dictionary that is exposed through PhoneApplicationService.State property. You can store the application-level state data to PhoneApplicationService.State property in the Deactivated event, and retrieve the data from PhoneApplicationService.State property in the Activated event. For more information see, How to: Preserve and Restore Application State for Windows Phone topic.

If your application has persistent data, you can store the data to isolated storage instead of using State dictionary. Isolated storage is a sandboxed file storage area on your phone's disk. It is analogous to the desktop file system. Data stored in isolated storage can take several seconds to load, so you should use it only for data that require potentially long-term storage and for non-serializable objects. Additionally, you should carefully consider where you put your isolated storage code in order to minimize the impact of any delays. For example, if you have a lot of application data to store, you should avoid saving it all at once upon application exit, and instead save it incrementally. In general, you should save data to isolated storage as soon as it becomes available, or as early as possible. For more information, see Isolated Storage QuickStart.

 

Page State

Page state is the visual state of a page in your application. When the user presses the Back button to return to the tombstoned application, the Windows Phone operating system will automatically display the last page in the application that the user was viewing. However, you're responsible for making sure that the page state is saved and restored so that it looks the same as it did when the user navigated away from it. Page state includes things such as contents of a text box and scroll position of a scroll viewer. This section will show you how you can save and restore the page state in order to provide a seamless experience for the user

To save and restore page UI state, you must use the page constructor, OnNavigatedTo method, and OnNavigatedFrom method. The page constructor is called on the first navigation to a page. OnNavigatedTo is called on every navigation to a page when the application and page have finished loading and are available for use. OnNavigatedFrom is called on every navigation away from a page when the application and page have not yet started unloading. You can initialize page-level information in the constructor, you can restore page state in the OnNavigatedTo method, and you can save page state in the OnNavigatedFrom method.

Page Events

To save and restore page state, you typically perform the following steps.

  • Add a Boolean member variable to the page (named newPageInstance in the code example later in this section) and set it to false. This variable will be used to determine if the UI state needs to be restored.
  • In the page's constructor, set the page-level variable to true. The constructor will be called when the page is created for the first time in an application instance or if the page is being recreated after the application was tombstoned. The constructor won't be called if the user simply navigates back from another page in the application to this one, because the page is already in memory.
  • Override and implement the OnNavigatedTo method. In this method, retrieve the page-level state data from the PhoneApplicationPage.State property.
  • Override and implement the OnNavigatedFrom method. In this method, store the page-level state data to the PhoneApplicationPage.State property.

The following example has two pages named home page and second page. When you click the Go to the Second Page button in the home page, the application navigates to the second page. The second page has a form with a text box, two radio buttons, and a check box. If you enter some data into these fields in the second page and then press the Start button to exit the application, the application goes into a tombstoned state. If you navigate back to the second page by using the Back button, you can see that the data that you entered before exiting the application are restored.

Page State Restored

The following illustration shows the behavior if you don't include code to restore the page state.

Page State Not Restored

Add the following code in the second page to save and restore the page state.

C#

public partial class SecondPage : PhoneApplicationPage
{
bool newPageInstance = false;
public SecondPage()
{
InitializeComponent();
newPageInstance = true;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (State.ContainsKey("textbox") && newPageInstance == true)
{
MyTB.Text = (string)State["textbox"];
MyRB1.IsChecked = (bool?)State["radiobutton1"];
MyRB2.IsChecked = (bool?)State["radiobutton2"];
MyCB.IsChecked = (bool?)State["checkbox"];
}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
newPageInstance = false;
State["textbox"] = MyTB.Text;
State["radiobutton1"] = MyRB1.IsChecked;
State["radiobutton2"] = MyRB2.IsChecked;
State["checkbox"] = MyCB.IsChecked;
base.OnNavigatedFrom(e);
}
}

Visual Basic

Public Partial Class SecondPage
Inherits PhoneApplicationPage
Private newPageInstance As Boolean = False
Public Sub New()
InitializeComponent()
newPageInstance = True
End Sub
Protected Overrides Sub OnNavigatedTo(e As System.Windows.Navigation.NavigationEventArgs)
If State.ContainsKey("textbox") AndAlso newPageInstance = True Then
MyTB.Text = DirectCast(State("textbox"), String)
MyRB1.IsChecked = CType(State("radiobutton1"), System.Nullable(Of Boolean))
MyRB2.IsChecked = CType(State("radiobutton2"), System.Nullable(Of Boolean))
MyCB.IsChecked = CType(State("checkbox"), System.Nullable(Of Boolean))
End If
MyBase.OnNavigatedTo(e)
End Sub
Protected Overrides Sub OnNavigatedFrom(e As System.Windows.Navigation.NavigationEventArgs)
newPageInstance = False
State("textbox") = MyTB.Text
State("radiobutton1") = MyRB1.IsChecked
State("radiobutton2") = MyRB2.IsChecked
State("checkbox") = MyCB.IsChecked
MyBase.OnNavigatedFrom(e)
End Sub
End Class

For more information on page state, see How to: Preserve and Restore Page State for Windows Phone.

 

Best Practices

The following are some execution model best practices that you can follow while developing a Windows Phone application:

  • When your application is launched, from either the tile or the installed applications list, the user must be taken to a consistent root experience. It should be clear to them that they are experiencing a new application instance.
  • When your application is activated from a tombstoned state, the user must be taken to an experience that is consistent with the one that was shown when the application was deactivated. It shouldn't be evident to the user that the application was terminated and restarted.
  • After an application has been tombstoned, the user may not return to the application immediately. For this reason, you should save persistent state to isolated storage both in the Deactivated event handler and in the Closing event handler. To avoid duplicating code, you may want to create a single method that saves persistent data to isolated storage and to call the same method from both event handlers.
  • Applications must complete all of the actions in the Deactivated event handler in less than 10 seconds. An application that takes longer than 10 seconds to complete its Deactivated handler will be force-terminated and will no longer be accessible via the Back button. It's recommended that you aim for a much shorter window when developing your application. If your application has more state data than can be saved in a few seconds, you may want to save incrementally to isolated storage while your application is running.

For more information see, Execution Model Best Practices for Windows Phone.

See Also

var gDomain='m.webtrends.com'; var gDcsId='dcschd84w10000w4lw9hcqmsz_8n3x'; var gTrackEvents=1; var gFpc='WT_FPC'; /*<\/scr"+"ipt>");} /*]]>*/
DCSIMG