Chapter 6: Application Lifecycle Differences Between Windows Phone 7 and the iPhone

Date: Tuesday, April 26, 2011, 12:00:00 AM

Tags: iPhone, WP7, Porting, Tombstoning

Table of Contents

In this chapter, we are going to look at the navigation model of the Windows Phone 7. We will examine the various application states needed to support the navigation model, and what the developer needs to do to support those application states and the transitions between them. We will then look at what the developer needs to do to duplicate iPhone multitasking.

iPhone and Windows Phone 7 Navigation Models

Technically speaking, both the iPhone and the Windows Phone 7 allow only one application to execute in the foreground at a time. The foreground application owns the screen and receives the touch events. Let us briefly review the iPhone execution model.

iPhone Execution Model

With iOS4, the iPhone introduced multitasking, with the ability to do fast application switching. When the user clicks the home button, instead of terminating, the currently executing application is put into a background running state. In this state, the application is expected to save the data. If the user switches back to this application, after using another application, the background application transitions to foreground and is made active again, at which time the user can resume where he/she was. Additionally, iOS4 also supports other forms of multitasking, such as task completion or background execution for applications using audio, location or VOIP.

Windows Phone 7 Navigation Model

In Windows Phone 7, the user can switch to another application in two different ways. The user can hit the start button at any time to reach the Start page and launch another application. The user can also use the back button to navigate out of an application.

For example, consider that the user is composing a blog post, using the WordPress application, and then hits the start button to reach the Start screen, at which time the WordPress application is deactivated. The user then opens up the Facebook application. At this time, the Facebook application is launched.

The hardware back button allows the user to navigate back between pages within an application, or across applications. In the above example, the user can hit the back button while in the Facebook application, to first reach the WP7 Start screen, and hit the back button again to go back to the WordPress application. The WordPress application would open with the compose screen, exactly how and where the user left it.

While WP7 does not support actual multitasking, the WP7 navigation model allows a natural navigation much like the browser back button. The application state is preserved as the user navigates across applications using the back button.

The following table provides an overview of various events and the behavior of the application on iOS and Windows Phone 7.

User Action or Event

iOS 4.0 Behavior

WP7 Behavior

An incoming phone call or SMS

Running application is moved to the background but running

Running application is deactivated

User Clicks the home button

Running application is moved to the background but running

Running application is deactivated

User Clicks another application from the multitasking menu

Background application is moved to foreground and made active to its original state

-

Navigation between applications using back button

-

Deactivated or tombstoned application is activated to its original state

Programming for application States and navigation

On both the iPhone and WP7, the developers need to take certain steps to support the application life cycle.

iPhone support for multitasking

In order to support fast application switching, iPhone application developers have certain responsibilities. When the application is moved to the background, they need to save the application state, which is then restored when the application is subsequently moved again to the foreground.

In particular, the application moving to background will receive a callback, applicationDidEnterBackground, at which time the application should do the bookkeeping, save the state and reduce the application memory footprint. When the user relaunches the application using the multitasking UI, the application will receive the applicationWillEnterForeground callback at which time the application should restore the state.

When the application is launched from the application icon, the application receives the applicationDidBecomeActive callback, at which time the application can initialize the state. When the application becomes inactive, due to an interrupt such as a phone call, it receives the applicationWillResignActive event at which time, so it can save the state, as it may be moved to the background.

Windows Phone 7 LifeCycle

Launching the Application When the user launches the application for the first time, the application receives the Application_Launching event. In order to provide fast startup response, the application should do little work in this event handler. In particular, it should avoid any web downloads or isolatedStorage (see below) data fetch operations. Once active, it can initialize the state or load any saved state.

Terminating the Application While the application is running, the user may terminate it by navigating out of the application using the back button. At this time, the application will receive the Application_Closing event. In response, the application should perform any cleanup and save the persistent application data to isolatedStorage.

Deactivating the Application and Tombstoning While the application is running, the user can hit the Start button or launch another application via launchers or choosers. The user may launch the browser by clicking on a link in the application.

Similar to an application that is closed, an application that is deactivated is also terminated. However, unlike a closed application, for a deactivated application, the OS stores a record (a tombstone) for the state of the application. This is maintained as part of the application back stack which is used to facilitate navigation using the back button.

In these cases, the application is sent an Application_Deactivated event, at which time the application should save all persistent data to isolatedStorage and all transient data, such as the values of page fields, using PhoneApplicationPage.state.

Reactivating the Application Upon completing the launcher, or the user navigating back into an application using the back button, the application will be reactivated. Upon reactivation, the application will receive the Application_Activated event. Since the application is being reactivated from a tombstone state, the application should load the persistent state data from the isolatedStorage and the transient state data from PhoneApplicationPage.state.

Windows Phone 7 Application State Transition Diagram

The following state diagram shows the various states and explains what the developer should do in response to various events.

clip_image002

WP7 LifeCycle and Tombstoning Example

Let us look at a simple example that illustrates the Windows Phone 7 state transitions and tombstoning. This is a one page shopping list application where the user can add items to the list. When the user leaves the application, the shopping list is saved automatically.

Saving the Application State

On the iPhone, you may be saving the state in a number of different ways. On the iPhone, using NSUserDefaults, using files in the Documents folder of the application, or using SQLLite are all possible ways to save application state data.

To save the persistent state of the application on WP7, i.e., the shopping list, we are going to use isolatedStorage. isolatedStorage is a safe storage that is accessible only to that application. It ensures that one application cannot affect another application. To save the state, we first get the isolatedStore for the application. We then create a file in isolatedStorage, in which to save the persistent state. To save the shopping list, we first serialize the list and then save it to the file.

public static void SaveShoppingList(ShoppingListInfo shoppingListInfo, string fileName) { 
    //Get the isolatedStore for this application 
    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { 

        // create a new file 
        using (IsolatedStorageFileStream fs = isf.CreateFile(fileName)) { 
            //and serialize data and save it 
            XmlSerializer xmlSer = new XmlSerializer(typeof(ShoppingListInfo)); 
            xmlSer.Serialize(fs, shoppingListInfo); 
        } 

    } 

} 

In order to save transient state, WP7 provides another class called PhoneApplicationService.State. We will see the use of this object below.

Terminating the application

When the user uses the back button to leave the application, the application is terminated. What the application should save during termination depends upon the nature of the application. In this example, we will save the work without asking the user so that when the user next opens the application, the shopping list is intact. In this example, we will not save any item that the user was typing in the item textbox. We use the helper method defined earlier to save the shopping list. Such cleanup and state saving may be performed in response to the Application_Closing event instead of OnBackKeyPress.

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { 
    base.OnBackKeyPress(e); 

    //do not save what is in the item, i.e. it is transient 
    txtItem.Text = ""; 

    //preserve data in persistent store 

    Utils.SaveShoppingList((App.Current.RootVisual as PhoneApplicationFrame).DataContext as ShoppingListInfo, "ShoppingListInfo.dat"); 

} 

This event is comparable to the ApplicationWillTerminate callback in versions prior to iOS4. In iOS4, there is no equivalent to this operation, as the state of the application will already be saved in response to the applicationDidEnterBackground callback.

Application Launching

When the application is launched from the Start screen, the application received the Application_Launching event. This is equivalent to the application receiving applicationDidFinishLaunchingWithOptions and applicationDidBecomeActive callbacks in iOS4.

During launch, we will examine whether any persistent data is available. If we find the persistent data, we will load it into the txtList textbox to preserve the shopping list. We first get the isolatedStore for the application. Using the isolated store, we check if the ShoppingListInfo.dat file exists. If it is available, we deserialize the data that was stored in the file and reload the ShoppingListInfo. The fields in the application are databound using the last line in this snippet. If you run the application, you will find that the shopping list is preserved, upon relaunching the application.

// 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) { 
    //Trace the event for debug purposes 
    Utils.Trace("Application Launching"); 

    //Create new data object variable 
    ShoppingListInfo shoppingListInfo = null; 

    //Try to load previously saved data from IsolatedStorage 

    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { 
        //Check if file exits 
        if (isf.FileExists("ShoppingListInfo.dat")) { 
            using (IsolatedStorageFileStream fs = isf.OpenFile("ShoppingListInfo.dat", System.IO.FileMode.Open)) { 
                //Read the file contents and try to deserialize it back to data object 
                XmlSerializer ser = new XmlSerializer(typeof(ShoppingListInfo)); 

                object obj = ser.Deserialize(fs); 

                //If successfully deserialized, initialize data object variable with it 
                if (null != obj && obj is ShoppingListInfo) 
                    shoppingListInfo = obj as ShoppingListInfo; 
                else 
                    shoppingListInfo = new ShoppingListInfo(); 
            } 
        } else 
            //If previous data not found, create new instance 
            shoppingListInfo = new ShoppingListInfo(); 
    } 

    //Set data variable (either recovered or new) as a DataContext for all the pages of the application 
    RootFrame.DataContext = shoppingListInfo; 
} 


clip_image004

Application Deactivation

Let us examine what happens when the user hits the start button while running the application. When the user hits the home button in the iPhone, the application receives the applicationDidEnterBackground callback. On WP7, the application will receive the Application_Deactivated event. In response to this event, we will save the entire application state, i.e. the shopping list as well as the anything entered in the item textbox. If this application is reactivated, we will restore both textboxes to provide the same experience as if the user had navigated back into the application.

We will also save the transient application state; for this, we will use the PhoneApplicationService.State object.

// 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) { 
    //Trace the event for debug purposes 
    Utils.Trace("Application Deactivated"); 

    //Add current data object to Application state 
    PhoneApplicationService.Current.State.Add("UnsavedShoppingListInfo", RootFrame.DataContext as ShoppingListInfo); 
} 

Application Activation

When the user uses back button to navigate into the application, the application receives the Application_Activated event. In response to this event, we will reload the data from the PhoneApplicationService.State object. If we find the necessary data, we will load the UI elements using that data. If we do not find any saved data, the fields will get initialized to blanks. If you run the application, then hit the home key and navigate back into the application using the back button, you will find that both the shopping item and the shopping list are preserved.

// 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) { 
    //Trace the event for debug purposes 
    Utils.Trace("Application Activated"); 

    //Create new data object variable 
    ShoppingListInfo shoppingListInfo = null; 

    //Try to locate previous data in transient state of the application 
    if (PhoneApplicationService.Current.State.ContainsKey("UnsavedShoppingListInfo")) { 
        //If found, initialize the data variable and remove in from application's state 
        shoppingListInfo = PhoneApplicationService.Current.State["UnsavedShoppingListInfo"] as ShoppingListInfo; 
        PhoneApplicationService.Current.State.Remove("UnsavedShoppingListInfo"); 
    } 

    //If found set it as a DataContext for all the pages of the application 
    //An application is not guaranteed to be activated after it has been tombstoned, 
    //thus if not found create new data object 
    if (null != shoppingListInfo) 
        RootFrame.DataContext = shoppingListInfo; 
    else 
        RootFrame.DataContext = new ShoppingListInfo(); 
} 

clip_image006

iOS and Windows Phone 7 State and Event mapping

The following table provides mapping between iOS callbacks and Windows Phone 7 events related to the application lifecycle. While Windows Phone 7 does not provide multitasking, support for navigation using the back button requires that the application save the state during application deactivation and reload it when the user reactivates the application.

iOS Callback

Windows Phone 7 Event

Notes

applicationDidFinishLaunchingWighOptions

-

applicationDidBecomeActive

Application_Launching

Load Application persistent state

applicationWillResignActive

-

applicationDidEnterBackground

Application_Deactivated

Save application state

applicationWillEnterForeground

Application_Activated

Reload application state

applicationWillterminate

Application_Closing
Save Application Persistent state

Summary

In this chapter we looked at the Windows Phone 7 application states and transitions between them. We looked at what the developer needs to do to support the Windows Phone 7 navigation model. While the application model differs between the iPhone and Windows Phone 7, the developer needs to preserve the application state in much the same manner when the current application is moved from the foreground and is deactivated.

Resources

1. Introducing the Windows Phone Application Life Cycle-Tombstoning

2. Execution Model for Windows Phone

3. Windows Phone Application Lifecycle

 
blog comments powered by Disqus