MOBILE

Working with the Windows Phone 7 Application Life Cycle (part 1) - Observing Application Life Cycle Events

2/18/2011 7:55:30 PM
To program responsive applications on a Windows Phone 7 device, you must be familiar with the concept of tombstoning on that platform. The simplest way to explain tombstoning is to describe it as an event that happens when your application loses focus on the Windows Phone 7 device, such as when a user invokes a launcher or a chooser, or presses the hardware Start button. When your application loses focus, the Windows Phone OS realizes that there is a good chance that the user will want to come back, or reactivate your application shortly, and he or she will expect to find it in its previous state. Therefore, instead of simply terminating your application as soon as it loses focus, the Windows Phone OS remembers its state and provides developers with a means to save session-related information to a custom State dictionary object. However, with tombstoning, there is always a chance that your application may never be reactivated. So, if there is data that needs to be permanently preserved within your application, you should save it to the isolated storage instead of the transient State object.

You will get to observe tombstoning at work shortly, but before that, you need to walk through a typical life cycle of a Windows Phone 7 application. Table 1 summarizes the application events that can occur during the execution of a typical Windows Phone 7 application. The table also describes the actions you as a developer should take when each of those events occurs.

Table 1. Applications Events, Triggers, and Actions
Application EventOccurs WhenYour Actions
Application_LaunchingThe user taps the entry for an application on the installed applications screen, and a new instance of an application is created.Do not read application settings from the isolated storage as that will slow down the loading process; do not attempt to restore transient state. When an application launches, it should always appear as a new instance.
Application_ActivatedFor this event to occur, two conditions must be met: (1) the user navigates away from your application, either by using a launcher or a chooser, or by starting another application and (2) the user then comes back to your application by either completing the launcher or chooser or using the hardware Back button. This event is not raised when an application is first launched.The application should allow the user to continue interaction as if she had never left the application; transient state information should be restored, but the application should not attempt to read the contents of the isolated storage to avoid potential slowdown.
Application_DeactivatedThe user navigates away from your application either by invoking a launcher or a chooser, or by launching another application. This event is not raised when your application is closing.You should save all transient (i.e., related to the current application session) state into the State dictionary. You should save persistent state to an isolated storage. Applications are given ten seconds to complete this event; after ten seconds, if this event is still not completed, an application will be terminated and not tombstoned.
Application_ClosingThe user uses the Back key to navigate past the first page of your application.Save all of the persistent state into the isolated storage.

In the next section, you will code and observe the conditions under which each of the events in the application life cycle is triggered.

1. Observing Application Life Cycle Events

To help you better understand the conditions under which tombstoning occurs and the events that are fired, let's enhance the application built previously in this article to trace the events raised within the application.

1.1. Enhancing the User Interface

You will enhance the application user interface by adding a text box and a button control to the design surface of MainPage.xaml to make it look similar to Figure 10-2.

  1. Launch Visual Studio 2010 Express, and open the previously created Tasks project.

  2. Double-click MainPage.xaml in Solution Explorer, and add a text box and a button to the design surface, as shown in Figure 10-2. Clear the Text property of the text box, and set the button's caption to "Launch Browser."

1.2. Adding Application Logic to Invoke WebBrowserTask Launcher and Log Events

Now, you will add logic to invoke a WebBrowserTask launcher and navigate to www.windowsphone.com, as well as add messages to print in the Debug window when various application life cycle events occur.

  1. Add the following using directive to the top of MainPage.xaml:

    using System.Diagnostics;

  2. You will launch the web browser when the user clicks the Launch Browser button. Double-click the Launch Browser button on MainPage.xaml, and make that button's Click event handler look like the following:

    private void button2_Click(object sender, RoutedEventArgs e)
    {
    WebBrowserTask webTask = new WebBrowserTask();
    webTask.Show();
    webTask.URL = "http://www.windowsphone.com";
    }

  3. Application life cycle events that we have discussed in the previous section are all automatically stubbed out (in other words, they contain basic method signatures without any implementation logic) in the App.xaml.cs file. Open that file (one way to do it is to right-click App.xaml and select View Code) so that you can modify those events by adding tracing logic to them.

  4. Within the Application_Launching event, add the following line of code:

    Debug.WriteLine("Application Launching");

  5. Within the Application_Activated event, add the following line of code:

    Debug.WriteLine("Application Activated");

  6. Within the Application_Deactivated event, add the following line of code:

    Debug.WriteLine("Application Deactivated");

  7. Within the Application_Closing event, add the following line of code:

    Debug.WriteLine("Application Closing");

Figure 1. User interface for application lifecycle test application

1.3. Running the Application

Before running the application, make sure to bring the Visual Studio Output window to the forefront—in Visual Studio, select Debug => Windows => Output on the menu bar. Press F5 to run the application that you have built in the previous steps and observe the messages displayed in the Output window.

  1. When the application first comes up, observe how an "Application Launching" message is printed in the Output window, indicating that the Application_Launching event has fired, but the Application_Activated event has not fired upon the initial launch of an application.

  2. Click the Launch Browser button to bring up Internet Explorer with the Windows Phone web site open. In the Visual Studio Output window, notice how the Application_Deactivated event fired as soon as the web browser was launched (see Figure 2), indicating possible tombstoning of your application.

  3. Click the Back button on the emulator screen. Notice how the Application_Activated event fires and prints a message in the Output window.

  4. Click the Start button, and observe how Application_Deactivated is fired again. If you click the Back button now, the Application_Activated event is triggered.

  5. Finally, click the Back button again. Since you have navigated past the first page of the application, the application is terminated, triggering the Application_Closing event and printing the corresponding message in the Output window.

To summarize the foregoing experiments, any time your application lost focus, an Application_Deactivated event was triggered. Any time an application gained focus (except for the initial launch), an Application_Activated event was triggered. These concepts are important to keep in mind as we discuss saving and retrieving state information in Windows Phone 7 applications in the next section.

Figure 2. Application life cycle illustrated by switching between applications on the phone

Table 2 summarizes the actions you took and the corresponding events raised within your application. You can reference Table 1 for actions to take to persist state when a given event is raised within your application.

Table . Summary of Your Actions and Resulting Application Events
Your ActionApplication Event
Pressed F5 to start the applicationApplication_Launching
Pressed Launch Browser button to launch IE on the phoneApplication_Deactivated
Clicked the Back button to go back to your applicationApplication_Activated
Clicked the Start buttonApplication_Deactivated
Clicked the Back button to return to your applicationApplication_Activated
Clicked the Back button to go past the first page of your applicationApplication_Closing
Other  
  •  Mobile Application Security : SymbianOS Security - Development and Security Testing
  •  Mobile Application Security : SymbianOS Security - Introduction to the Platform
  •  Java Mobile Edition Security : Permissions and User Controls
  •  Integrating Applications with the Windows Phone OS : Working with Launchers and Choosers
  •  Introducing Windows Phone 7 Launchers and Choosers
  •  Java Mobile Edition Security : Development and Security Testing (part 3) - Code Security & Application Packaging and Distribution
  •  Java Mobile Edition Security : Development and Security Testing (part 2) - Reverse Engineering and Debugging
  •  Java Mobile Edition Security : Development and Security Testing (part 1) - Configuring a Development Environment and Installing New Platforms & Emulator
  •  Java Mobile Edition Security : Configurations, Profiles, and JSRs
  •  Programming the Mobile Web : Performance Optimization
  •  Programming the Mobile Web : Testing and Debugging (part 3) - Client-Side Debugging
  •  Programming the Mobile Web : Testing and Debugging (part 2) - Server-Side Debugging & Markup Debugging
  •  Programming the Mobile Web : Testing and Debugging (part 1) - Remote Labs
  •  Windows Phone 7 : Working with Controls and Themes - Adding Transition Effects
  •  Windows Phone 7 : Working with Controls and Themes - Understanding Frame and Page Navigation
  •  Windows Phone 7 : Working with Controls and Themes - Panorama and Pivot Controls
  •  Programming the Mobile Web : Widgets and Offline Webapps - Platforms (part 5) - Windows Mobile & BlackBerry
  •  Programming the Mobile Web : Widgets and Offline Webapps - Platforms (part 4) - Windows Mobile & BlackBerry
  •  Programming the Mobile Web : Widgets and Offline Webapps - Platforms (part 3) - webOS & Android
  •  Programming the Mobile Web : Widgets and Offline Webapps - Platforms (part 2) - iPhone, iPod, and iPad
  •  
    Top 10
    Smart, But Not Pricey : LG Optimus L7, Nokia Lumia 610, Sony Xperia U, Micromax A90S, BlackBerry Curve 9320, Nokia Lumia 710
    Acer Iconia W510 - Multi-Faceted Windows Tablet
    The Big Show: LG Optimus Vu
    Edifier E10 Exclaim - Exclamation Mark
    If It Bleeps We Can Mix It (Part 2)
    If It Bleeps We Can Mix It (Part 1)
    Jabra SOLEMATE Bluetooth Portable Speaker
    Projecting Movies From Smartphone – Sharp BD-AMS20S
    Sharkoon X-Tatic SP Plus - Talk About Lots Of Cables
    Audio Technica ATH-FC707 - No Headline, Too Busy Enjoy Music
    Most View
    - Mobile Application Security : SMS Security - Overview of Short Message Service
    Gorilla Gondola
    IIS 7.0 : Runtime Web Server Extensibility (part 3) - Common Module Management Tasks
    Managing Alarms - Take Control Of Your Device’s Alarm
    Tokina AT-X 17-35mm f4 Pro FX (Part 1)
    iPhone 3D Programming : Textures and Image Capture - Texture Compression with PVRTC
    Off The Shelf Or Self- Build? (Part 1)
    Sony Xperia P Review (Part 2)
    Protecting SQL Server Data : SCHEMA ARCHITECTURE STRATEGIES - Using Views
    Atomic Learning - Educational Technology
    Windows Azure : Understanding the Blob Service
    Lenovo IdeaPad S400 - Stylish And Affordable Laptop
    Windows 7 : Managing Your Schedule - Printing Calendars
    IIS 7.0 : Managing Configuration - Delegating Configuration (part 2)
    The 30 Most Important Technology Trends (Part 1)
    Lenovo ThinkPad Twist - New Spin On Laptop Norms
    Olympus SZ-31 MR - Creativity Unleashed
    John G Moore’s Creative Outlet & Landscape Work (Part 1)
    Microsoft XNA Game Studio 3.0 : Displaying Images - Using Resources in a Game (part 1) - Loading XNA Textures
    IIS 7.0 : Configuring IIS Logging