(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

WP7 for iPhone and Android Developers - Introducing the Execution Model

(1 votes)
Kevin Hoffman
>
Kevin Hoffman
Joined Feb 01, 2011
Articles:   10
Comments:   1
More Articles
1 comments   /   posted on May 26, 2011
Categories:   Windows Phone , General

This article is part 7 of a 12-part article series on Windows Phone 7 for iPhone and Android Developers.

This article provides an overview of the Windows Phone 7 execution model. Knowing how your application starts, suspends, resumes, and interacts with the OS will help make your applications better behaved citizens which will, in turn, make your customers happier. Even now, months after the first devices were released, there are applications written by large companies that don’t properly take advantage of the execution model. Have you ever used a weather application that insists that the weather outside is still cold and snowing even though you’re outside on your deck grilling? This is because the application was suspended and hasn’t bothered to refresh its data from the internet yet. This problem is not specific to WP7 – plenty of iPhone applications either pre-date multitasking or don’t properly respond to suspend and resume events.

When we’re done with this article, you should have enough information to make sure that your application isn’t one of the ones that people complain about and that your applications continue to provide the best user experience possible.

Review of iPhone Multitasking

As many of you already know, when the iPhone first came out there was no SDK – developers were forced to make web pages that looked like native iOS applications. Then, when the SDK first came out there were no third party multi-tasking capabilities. Eventually, third party application developers (like many of you) were given the ability to participate in background audio, allowing applications like Pandora to continue playing music while you were free to browse web pages or catch up on your e-mail. Finally, with the release of iOS 4, third party developers were given multiple options for simulating background processing or actually performing background tasks.

As this article is about WP7 and not iPhone, I won’t go into too many details. The important point that I want to get across is that even though multi-tasking is possible on the iPhone, the most developer and device-friendly options for background processing typically don’t involve real multi-tasking, they involve simulations or other implementations that look like multi-tasking to the end users but aren’t what developers think of as true pre-emptive multitasking.

For example, one of the biggest reasons developers want background processing is so that their applications can wake up to perform some task at scheduled intervals. iOS now supports the notion of local notifications, which can be scheduled to allow the application to start itself back up again at scheduled intervals. Other applications wanted it so they could alert users when their location changed in some meaningful fashion (e.g. you just got within 20 miles of a super bargain or you’re near a house that’s for sale, etc). iOS now supports the ability to notify applications when significant changes to the device’s location occur, giving applications the ability to respond accordingly.

Again, the point here is that in many cases when you think you need real, true multi-tasking and background processing there are other more cost- and energy-efficient means available to you. This applies to Windows Phone 7 as well.

Introducing the Windows Phone 7 Application Life Cycle

The preceding diagram illustrates a (somewhat simplified) view of how Windows Phone 7 applications work and how they transition to and from the various application states. Knowing these application states and what your application can and should do during these transitions might make the difference between you building an average application and you building an extremely powerful and reliable application. This next section of the article is a brief overview of the application states and their transitions.

Launching

When an application is launched through any means except the use of the back button to navigate backward to a previously open application, then the application is considered to be in the “launched” state. This can be done by a user tapping the application’s tile on the home screen or the application icon on the application list or even if the user taps a toast notification that is associated with the application.

Any code that you execute during the application’s Launching event will be executed during each of these possible start-up scenarios. Do not put code that manipulates your user interface code in this event – wait until the Loaded event of the appropriate WP7 page fires to ensure that all the controls that need to be instantiated are available. Additionally, do not access isolated storage during the Launching event because this event must finish before your UI can be displayed and access to isolated storage is typically a slow and expensive process that could make your application startup appear sluggish.

Running

After the Launching phase is complete, the application is considered to be running. During this state is where the users will interact with your application. Its UI is instantiated, loaded, visible, and interactive.

Activating

When a user uses the back button (or other means) to return to a previously Tombstoned (discussed shortly) application, the application is activated rather than launched and the Activated event is fired. This event is different from the Launching event in that it provides the application with access to previously saved state information that was stored when the application was suspended or Tombstoned. This state information should be small, scalar details like integers and strings – it should be just enough information to allow your application to do what needs to be done after activation. If you can avoid using this state you should, but it is there as a last resort in the State property of the PhoneApplicationService class.

Deactivating

When an application that is running in the foreground is replaced by another application such as when a user presses the home/start button, a launcher or chooser gains focus and assumes the foreground, or when an idle timeout causes the phone to lock.

When an application is deactivated, the Deactivated event is fired and, as mentioned in the previous section, the application is given a chance to store last-minute state information in the PhoneApplicationService class. It is also given the opportunity to smoothly shut off any active network connections or timer-based activities that might otherwise be terminated.

Closing

If an application ceases to be the foreground application (current versions of WP7 only allow one application at a time – this will likely change with future releases like the “Mango” release) and no other application takes its place then rather than being deactivated, the application receives the Closing event. This can happen as a result of a user hitting the back button to go back beyond the home/start page of the application. During the Closing event the application should make sure that any important information currently in memory is persisted to isolated storage somehow. You should not use this event to make outbound network calls because your application only has a limited time in which to close before it is forcibly shut down. If you need to make a network call, store what you plan to do in isolated storage and then make that call the next time your application starts.

Tombstoned

I have mentioned the concept of Tombstoning a few times in this article. When an application is deactivated, it is given a chance to save any important state and it will remain deactivated for a short period of time. This “grace period” window is used to account for when a user leaves an application and then quickly re-enters the application. To make sure this process is as quick as possible, the application remains deactivated for a little while before being tombstoned.

If a deactivated application isn’t re-activated within a short period of time, then it will be Tombstoned. This refers to the process by which the deactivated application is terminated. The process, threads, and memory associated with that application is reclaimed. However, the transient state information (remember the State property of the PhoneApplicationService class?) and other low-level details are all saved for future use.

When a user starts an application that has been Tombstoned, instead of the Launching event being raised, the Activated event is raised and the information originally left behind (“etched on the tombstone” as it were) is used to restore application state.

Using the Execution Model in Code

The easiest way to see how the various stages of the application life cycle interact with each other is to put some debug tracing in the relevant application events. When you create a new WP7 application, your App.xaml.cs file already contains blank override methods:

  • Application_Launching
  • Application_Activated
  • Application_Deactivated
  • Application_Closing

For starters, put a Debug.WriteLine in each of those methods indicating which event is called and then go experiment. Launch the application from the debugger. Then, use the back button on the simulator to leave foreground without replacing the application (this should trigger the Closing event). Now re-launch the application – which event do you think should be triggered?

Another interesting one to try is to hit the back button and then hit the home button rapidly. Try some strange combinations and see what you can do and see if you can spot when your application gets a Tombstone versus when your application is just deactivated.

Next, put the following code into your Deactivated event handler below your debug statement:

 1: PhoneApplicationService.Current.State["test"] = 42; 

And put the following code into the Activated event handler below the first debug statement:

 1: if (PhoneApplicationService.Current.State.ContainsKey("test"))
 2:     Debug.WriteLine(PhoneApplicationService.Current.State["test"]);

Also, if you are ever curious how the application was started and you aren’t writing code directly in an application event handler, you can always interrogate the application’s startup mode with the PhoneApplicationService.Current.StartupMode property. This property is an enum that can either be Launched or Activated, telling you whether the currently running instance of the application was started fresh (launch) or resumed from deactivation or tombstonining (activated).

Summary

As mentioned at the beginning of this article, understanding the various states in which your application can reside and how it gets into and out of those states is essential to making sure your application can handle all of the edge cases. You can’t just assume that everyone starts a fresh copy of your application and then shuts it down completely when they’re done with it like what happens when you’re debugging in the simulator. Applications can be resumed from an in-memory deactivated state or they can be revived from a tombstone or they can be launched fresh. Applications are given opportunities to clean up their messes when being deactivated or when closing.

In the future, when new versions like the “Mango” release come out with so-called “true multi-tasking” features, the application life cycle may change. However, knowing how to harness the current application life cycle will only put you in a better position to understand and utilize multi-tasking and background processing features that might appear in future versions of WP7.

About the Author

Kevin Hoffman (http://www.kotancode.com/) is a Systems Architect for Oakleaf Waste Management (http://www.oakleafwaste.com/), freelance developer, and author of multiple books including the upcoming WP7 for iPhone Developers and co-author of books such as ASP.NET 4 Unleashed and SharePoint 2007 Development Unleashed. He is the author of the Kotan Code blog and has presented at Apple's WWDC twice and guest lectured at Columbia University on iPhone development.

 


Subscribe

Comments

  • -_-

    RE: WP7 for iPhone and Android Developers - Introducing the Execution Model


    posted by Ray Akkanson on May 28, 2011 21:50

    Mango will be a Iphone and Android Killer. And wait for Windows 8... :)

    Ray Akkanson

Add Comment

Login to comment:
  *      *       

From this series