Qt to WP7 - Chapter 5: Introducing Windows Phone Application Life Cycle

Date: Monday, September 19, 2011, 5:26:15 PM

Tags: Qt

Table of Contents

< Back to Qt to WP7 Guide contents

The Windows Phone (WP) execution model is designed to improve user experience by cutting down on response time and offering seamless navigation among applications. Due to fundamental differences in application execution architecture, WP application's life cycle differs largely from the Symbian Qt application's life cycle.

Executing Multiple Applications in Windows Phone

The following chapters describe how WP OS platform execution model controls the execution of multiple WP applications.

Multitasking in Windows Phone and Symbian Qt

To enable seamless navigation, WP7 activates and deactivates applications dynamically by limiting the phone to run one application at a time. WP7 prioritizes the foreground application and tombstones other open applications.

Tombstoned application is not preserved in memory, but information about the application state is stored and resumed when WP7 activates the application again. This WP7 behavior differs from Symbian Qt platform, where several applications may be up and running at the same time and the user may switch between active applications.

However, newly introduced WP7.1 OS architecture allows simultaneous execution of multiple applications, thus providing multitasking and application switching functionality similar to Symbian Qt platform. In WP7.1 OS, applications are typically put into a dormant state when the user navigates away from the application.

In the dormant state, execution of the application's code is stopped, but the application remains intact in memory. If an application is dormant and the user navigates back to the application, the application resumes and the state of each page in the application is automatically restored to the state before the user navigated away.

Tombstoning of Applications in Windows Phone

Tombstoning is a process through which WP7 deactivates an application when a user navigates away from it. WP7 keeps a record of the tombstoned application and stores the latest data and the state of the application. If the user returns to a tombstoned application by using the hardware Back button, WP7 reactivates this application and the application can use the preserved data to restore state.

In WP7.1, when user navigates away from the application, the operating system will attempt to put the application into a dormant state. Dormant state applications can be reactivated and automatically restored to the previous state using the hardware Back button, either by using normal press to return to application or by using long press to activate the application switch mechanism. WP7.1 OS may also tombstone dormant state applications in cases such as freeing up memory for other applications.

The following table compares the application execution behavior between Symbian Qt and Windows Phone 7 & Windows Phone 7.1.

Symbian Qt Behavior

User Action or Event

Windows Phone 7 Behavior

Windows Phone 7.1 Behavior

Running application is moved to the background but it remains active

An incoming phone call or SMS

Running application is deactivated to tombstoned state

Running application is deactivated to dormant state

Running application is moved to the background but it remains active

User presses the Home button on the phone

Running application is deactivated to tombstoned state

Running application is deactivated to dormant state

Background application is moved to foreground with the current state

User starts another application from the multitasking menu

Multitasking is not supported in WP7

Dormant state application is moved to foreground and automatically restored to preserved application state

Background application is moved to foreground with the current state

User navigates between applications using the Back button on the phone (Tool bar Back button in Symbian)

Tombstoned state application is moved to foreground and restored to the state stored during deactivation

Dormant state application is moved to foreground and automatically restored to preserved application state

Platform behavior on certain user actions and phone events

Life Cycle Events of a Windows Phone Application

This chapter introduces the events taking place during the life cycle of a WP application. The following picture illustrates the life-cycle and states of a WP application.

Life-cycle and state transitions of a Windows Phone application

Launching

In WP, the user can launch applications from the installed Applications List, from a tile on the Start screen, through a toast notification or through menus. An application is launched when it is started by other means than navigating back to it using the hardware Back button. Whenever the user launches an application, WP creates a new instance of the application.

The Launching event is raised even before application is visible to the user. In the handler for this event, you should execute as little code as possible. Storing data or performing network operations at this state may increase the startup time of the application. For the best performance and user experience, resource-intensive tasks should be performed on a background thread after your application has loaded.

Running

After launching, the application goes into the Running state. In this state, the application manages its own state as the user navigates through the different pages of the application. Application continues to run until the user navigates forward away from the application or backwards past the first application page.

In the Running state, settings and the persistent data are saved. This reduces the data that you need to save when the application's state changes. However, the decision to save data in this state is optional. If the size of the persisted data is not large, you don't need to save the data.

Closing

Your application comes across the Closing event when the user presses the hardware Back button while located in the application's first page. In the handler for this event, you can save data that should persist across instances to the isolated storage.

There is a time limit of 10 seconds for applications to complete all application and page navigation events. If this limit is exceeded, the application is terminated. For this reason, it is a good idea to save persistent state during Running state of the application and avoid having to do large amounts of file I/O in the Closing event handler.

Deactivating

WP deactivates your application in the following scenarios:

·The user opens another application

·The user locks the phone screen

·An event accesses the Launcher or Chooser APIs

·The user presses the Windows button to open the Start screen on the phone

·The user presses the Search button on the phone

In the handler for Deactivated event, you must save any application state so that it could be restored at a later time. Windows Phone applications are provided with the State object, which is an in-memory dictionary you can use to store and restore application state without resource-intensive file operations.

It is possible for an application to be completely terminated after Deactivated event. When an application is terminated, its state dictionary is not preserved. For this reason, you should also store any state that should be persisted across application instances to isolated storage during the Deactivated event.

After the Deactivated event your application enters the dormant or tombstoned state.

;

Activating

The Activated event is raised when the user returns to a dormant or tombstoned application. Applications should check the event arguments to determine whether the application is returning from being in dormant or in tombstoned state.

If the application is returning from dormant state, the state of application has been automatically preserved by the WP operating system. If the application is returning from tombstoned state, the application should use the State dictionary to restore its state before deactivation.

Applications should not perform resource-intensive tasks such as loading from isolated storage or using network resources in the Activated event handler because it increases the time it takes for the application to resume. Instead, these operations should be performed on a background thread after the application has been activated.

;

Event Handlers in Windows Phone Applications

In Symbian Qt, each application has own process and main thread that controls application life-cycle, resources and state. Application execution is controlled in event loop based on different application-specific and system-wide events such as signals and slots, commands, Window server events, system events, domain-specific events and touch-specific events, most of them asynchronous.

WP application life-cycle is largely different from the Symbian Qt application life-cycle. In WP, your application is in transition between the active and inactive states. You can implement handlers for application's life-cycle events and page events to save and restore application & page states.

The following table introduces WP application life-cycle events &Pageclass event handler methods compared to somewhat similar Symbian Qt methods & events.

Windows Phone State

Windows Phone Application Events

Windows Phone Page Methods

Symbian Qt Events

Launching

Application_Launching

InitializeComponent()

QEvent::ApplicationActivateevent

Running

; ;

QObject::eventFilterevent loop

Deactivated

Application_Deactivated

OnNavigatedFrom

QEvent::ApplicationDeactivateevent

Activation

Application_Activated

OnNavigatedTo

QEvent::ApplicationActivateevent

Closing

Application_Closing

OnNavigatedFrom

QEvent::ApplicationDeactivateevent

WP application life-cycle events andPageclass event handler methods

In addition to WP application life-cycle events and event handlers introduced in the previous chapter, WP application page events can be managed using WP page event handler methods. TheInitializeComponent()method in WP is used in the constructor of thePageclass to initialize variables. You need to get theApplication_Launchingevent to define the global variables inInitializeComponent()method.

Of the other WP page event handling methods,OnNavigatedTois used inPageclass when a page becomes the active page in a frame. Respectively,OnNavigatedFrommethod is used when a page is no longer the active page in a frame. These methods have close relationship with application eventsApplication_Launching,Application_Deactivated,Application_ActivatedandApplication_Closing.

TheOnNavigatedTo(NavigationEventArgs)method in WP is called whenever the user navigates to an application page i.e. when the application is first launched, when the user navigates between the pages of the application or when the application is re-launched after being made dormant or tombstoned. In this method, applications should check whether the page is a new instance. If it is not, state does not need to be restored. If the page is a new instance and there is data in the State dictionary for the page, then the data should be used to restore the state of the page's UI.

TheOnNavigatedFrom(NavigationEventArgs)method in WP is called whenever the user navigates away from an application page, as a result of normal page navigation within your application or when the application is deactivated. Whenever this method is called, your application should store the page state so that it can be restored if the user returns to the page.

Implementing application life-cycle management

This chapter illustrates the WP application life-cycle management and application & page state handling on application code level. For that purpose we use our ShoppingList example application, WPPageclass event handler methods and Isolated Storage for persistent data. Purpose of the code snippets is to provide plain and simple examples of Isolated Storage andPageclass event handler method usage.

Refer to previous chapters and see Execution Model Overview for Windows Phone for more comprehensive information about Windows Phone application execution model and application & page event handling. Execution Model Best Practices for Windows Phone provides useful hints and tips for execution model implementation strategy in your own applications.

Saving the Application and Page State Data

To save the persistent state data of a WP application, you can use Isolated Storage. Isolated Storage is a safe application-specific storage space that is not accessible to other applications. All WP application I/O operations are restricted to Isolated Storage and do not have direct access to the underlying OS file system or to the Isolated Storage of other applications. The following picture illustrates the options for using Isolated Storage.

Data types that can be stored to Isolated Storage

To implement the saving of persistent application and page state data, you need to obtain the Isolated Storage for the application. After that, create a file or use Key/Value pairs in Isolated Storage to store the persistent state data. In our ShoppingList example application, we save the shopping list data to a file.

To obtain Isolated Storage and to store the shopping list to a file, do the following in ShoppingList example application:

44.Add the followingusingdirectives to your MainPage.xaml.cs to include namespaces for Isolated Storage handling:

using System.IO;
using System.IO.IsolatedStorage;

45.To determine if the page is a new instance, add the following Boolean variable to theMainPageclass definition in MainPage.xaml.cs.

public partial class MainPage : PhoneApplicationPage
{
bool _isNewPageInstance = false;

46.In the constructor of theMainPageclass, set theisNewInstancevariable to true.

The constructor will be called only when the user is launching the ShoppingList application. If the user is simply navigating back to theMainPageof ShoppingList application, data is not restored.

47.TheOnNavigatedTomethod is called whenever the user navigates to an application page. Add theOnNavigatedToimplementation toMainPageclass. Use the Boolean variable_isNewPageInstanceto determine if the page is a new instance. If the page is new and previous Isolated Storage file exists, restore the data from Isolated Storage file toMainPagetxtListtext box. Refer to the code snippet below.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    // If _isNewPageInstance is true, the page constructor has been
    // called during application launching.
    // Application data may need to be restored from the Isolated
    // Storage.
    if (_isNewPageInstance)
    {
        // Obtain the Isolated Storage for the application.
        IsolatedStorageFile myStorage = ew
        IsolatedStorageFile.GetUserStoreForApplication();
        // Try to load previously saved data from Isolated Storage.
        // Check if file exists.
        if (myStorage.FileExists("ShoppingList.dat"))
        {
            // Create StreamReader for Isolated Storage file and
            // specify file options.
            StreamReader myStorageReader = new
            StreamReader(myStorage.OpenFile("ShoppingList.dat",
                        FileMode.Open));
            // Read the data from Isolated Storage file and output it
            // to UI.
            txtList.Text = myStorageReader.ReadToEnd();
            //Close the StreamReader
            myStorageReader.Close();
        }
    }
    // Else, if _isNewPageInstance is false, the application is
    // reactivated. No need to restore application data.
    // Set the _isNewPageInstance to false.
    _isNewPageInstance = false;
}

48.TheOnNavigatedFrommethod is called whenever the user navigates away from an application page. Add theOnNavigatedFromimplementation toMainPageclass. Store theMainPagetxtListtext box data to Isolated Storage file. Refer to the code snippet below.

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    // Store the member data to the Isolated Storage, in case the
    // application is never re-activated.
    // Obtain the Isolated Storage for the application.
    IsolatedStorageFile myStorage =
    IsolatedStorageFile.GetUserStoreForApplication();

    // Create StreamWriter for Isolated Storage file and specify file
    // options.
    StreamWriter myStorageWriter = new
    StreamWriter(myStorage.OpenFile("ShoppingList.dat",
    FileMode.OpenOrCreate));
    // Store the UI data to Isolated Storage file.
    myStorageWriter.Write(txtList.Text);
    // Close the StreamReader.
    myStorageWriter.Close();
}

Note: To manage transient application and page state data in WP applications, useStateproperty inPhoneApplicationServiceandPhoneApplicationPageclasses.Stateproperty is a dictionary used for saving and restoring data duringApplication_ActivatedandApplication_Deactivatedevents.

;

Summary

To know more about the execution model for Windows Phone, visit:

Other Resources you may find useful:

< Back to Qt to WP7 Guide contents

 
blog comments powered by Disqus