Lifecycle Constraints in Windows Phone 7

When working with the execution model in Mango there is some key constraints that you should take into account. If you’re familiar with the Phone 7 OS you may be aware of these points.

Deactivation -> Dormant -> Tombstoned -> Closed

When you’re application is deactivated, it immediately goes into Dormant mode it later maybe go into Tombstoned and even later it may get Closed.

So when handling the deactivated event it’s important that you save any states that should span application instances such as user settings, disk storage as well as transient dictionaries so that state can be later restored even if the application gets closed by the OS.

In the launching event handler you should perform as little work as possible as long running test can delay the application startup. Likewise, the activation handler executes the four execution startup, so any work perform in it should complete quickly otherwise you should upload it to a separate thread. Just like in WP7 all event handlers and navigation methods should complete within 10 seconds or else the OS will terminate the application. Likewise, codes that runs in deactivation or closing should only complete within 10 seconds. Running code on a separate thread does not help in these cases since these applications are being stopped anyway.

So, if large data writes are necessary it’s best to save data incrementally throughout application execution instead of saving them all in deactivation.

Launchers and choosers will deactivate app and this is a change from WP7

When a launcher or chooser is open by the user the application will go into dormant mode, this behavior is a departure in WP7 where the application actually continued to execute code although this behavior was undocumented. Similarly, when the phone lock screen is engaged the application also goes in Dormant mode.

Unless the application is allowed to run under lock screen. If that’s the case the application will continue running and will not be deactivated which makes sense. Now to allow for an application to continue to run when the lock screen is engaged you need to set the ApplicationIdleDetectionMode property of the PhoneApplicationService object to devalue disabled. You can also handle the obscured and unobscured events that are exposed by the root frame to minimize CPU and battery consumption while the application is locked.

Managing Application State in Windows Phone 7

Application state is not related to a particular page, we handle the life cycle events launching, deactivated, activated, and closing to perform state saving and restoring operations. These events are raised by the operating system. These are still the same and unchanged. Event handlers are stabbed out by default.

Going back to the Life Cycle Graph that I posted earlier. Remember that the deactivated event is raised before the application goes into Dormant state so this is our last chance to save application data to the phone application services state dictionary which will persist data across deactivation just like it’s Page State counterpart.

Now if and when the application gets reactivated like the user hits the back button, the activated event is raised early on before any page is constructed and so before any pages OnNavigatedTo is called. This is where we get to restore global application state before we handle any page level state.

It’s important to remember that the activated event will be raised on activation whether the application is returning from tombstone or dormant mode.

Here again, if the application was merely put to sleep in dormant mode it was never tombstoned no state restoration is necessary, since the application’s memory image is preserved. And we can test for that with

ApplicationEventArgs.IsApplicationInstancePreserve flag of Deactivated Args parameter that’s passed in to the activated event handler. As the name of property implies, a true value indicates that the application was frozen and preserve in memory and not tombstoned. Finally, in the closing event handler we can save our application’s persistent data if any to permanent storage before the application closes for good.

Page States C# code in Windows Phone 7

In this post we’re gonna look at Page states and the Mango Life Cycle.

Let’s create a new project and let’s select the default template for Windows Phone Project.

If you’re new to Windows Phone 7 SDK, this time you get the chance to select whether the Windows SDK will be 7.1 as Mango as suppose to 7.0.

Let’s create two pages for our demo app.

In our MainPage.xaml let’s try adding a HyperLink Button linking it to our page 1, so in our xaml.

Now on page 1 let’s create another hyperlink button where it will link us to page 2.

Now if we run our application and if we click the hyperlink button we will navigate forward to page 1.

This text box represent page state. Now as a user, we can input on the text box to fill up something.

Now in 7.0 what we happens is that even if the application gets deactivated by user pressing the Start/Search button or the phone is receiving an incoming call and returns back to the application is that the user’s input text should be saved and not load the default value which is an empty string. That is where we handle the application life cycle.

In Mango 7.5, if you try to press the search/start button and press the back button that process is now called the Fast App Resume. The reason is that by default, the debugger simulates dormancy (Dormant state) when the application gets deactivated and that is the reason the page state is restored even if you did not handle anything in your App.xaml

Note: As we know there are chances that in case the operating system runs low on resources that are dormant applications will get tombstoned in the later state.

The question now is, so how do we test what happens with our page state if that happens?

– A typical scenario is that we run a bunch of different applications and hope that the OS run out of resources but fortunately there is an easier way to do this.

Let’s try to simulate this by going to the Properties of our Project.

Right click -> Select Properties -> Debug tab

Now notice in our debug window is that there is a check box to check whether we want the application to run tombstoning upon deactivation or not.

Remember in my previous post that I mentioned that when an application is tombstoned, it automatically kills the threads and processes. So if we try to return back to our application it will create a new instance of the threads and processes and it takes MORE TIME. This scenario is what is happening in Windows Phone 7

Here is the code for us to implement saving page states in Mango it’s the same with 7.0…

In our Page1.xaml.cs

Again, remember that when the application is tombstoned it CREATES a new instance of the threads and processes, so everything is loaded by default.

In the code shown above, we created a boolean variable where it checks whether the application is a new instance or not.

Now where do we Save and Restore Page states? Remember the OnNavigatedFrom and OnNavigatedTo methods that you can override?

  1. OnNavigatedFrom is fired if the application has switched to another page or exits the current page. Let’s say going to Page 2.
  2. OnNavigatedTo is fired if the application is going back to the page, let’s say you press the start button and launches again the application.
  3. State[“”] dictionary is now what you use to save and restore page state.

In this post, you should now have an idea on how EASY it is to handle page states in Mango as opposed to 7.0.

Navigation Methods in Windows Phone

You might now be wondering if you have been following my post is that..

When do you save a page state?

Assumming our application has a page state that it needs to maintain let’s look at when to save and restore it. First let’s consider when to page state from the OnNavigatedFrom method the purpose of saving page state is to able to restore visual state should deactivation occurs, therefore we want to save page state whenever the page is either navigated away from or being deactivated.

If navigating back however, so if the user hits the back button page state should not be saved from user’s perspective, the implicit agreement is that by pressing the back button the user is leaving the current page and if the user returns to it he expects a fresh instance of the page. And that’s the way how the navigation system works. Pressing the back button either navigates back from the history of stack or exits the applications. In both cases, the current page will get removed from the stack and the page instance is destroyed. So the next time is navigatedTo a new instance is created. There are code we can detect whether the user is navigating back by taking the navigationMode property of the OnNavigatedFrom methods navigation events args parameter, the navigation mode enumeration indicates the direction of the current navigation operation. So if the value is back so we can skip saving page state, otherwise we should go ahead and save it since that means the user is navigating forward and there’s a chance that he will be returning to the page at a later stage.

We can use the state dictionary of the PhoneApplicationService class to persist page state to memory the dictionary will be persisted across deactivation even if the application is tombstoned at a later stage so that we can later retrieve it on reactivation.

When to restore a page state?

First we need to understand in which cases a new instance of a page is constructed when navigating to it. A page is instantiated when reach through forward navigation or the page is the application’s main page when the application is first launch. In the following graph, the yellow arrow indicates when an instance of a page is created so again, backward navigation does not result into a new instance of the page being constructed.

Now when navigating back to the page after the application is being deactivated the page may, or may not be a new instance depending whether the application is tombstoned or not. Most of the times the application will just be put in dormant state, so as we’ve seen this made the application preserve intact in memory. And so when the user returns to the page, the same instance is revived. If on the other hand, at some point later the application is later tombstoned then when the user returns a new instance of a page is created on activation since the application is reconstructed a new one. So page state needs to be restored when the page is a new instance and state was previously saved in the previous dictionary. That’s the only case when returning the page from tombstone mode.

In your applications you can define a simple flag to test whether a current page is a new instance or not, which helps in deciding whether page states should be restored. Know that if you have an existing applications that target Windows Phone 7 typically no change would be necessary when regards to page state, since returning from dormant state scenarios which is new in mango is handled in the same way as the returning back from another page scenario which already exist in Phone 7.

Follow me on my next post as I teach you how to implement this in Visual Studio.

Page State in Windows Phone

Now you may be wondering how the Mango Life Cycle affect our lives as developers, well the applications we build need to take that model into account. We need to anticipate that is a common for a user to hop over to another application using the start or to hit the search button for example. Also there are also common mechanism that will trigger deactivation in our application.

For example, the phone receives an incoming phone call or the user may open a launcher or chooser. Just like the people who build the platform, as developers our objective is to make the user experience SEAMLESS as a result, when the application getes deactivated we need to save our application specific data and we restore it if and when the application is reactivated. There are two types of state that we need to manage in our application, page state and application state.

Page state is a visual state of the page and its UI elements. In mango, we save and store page state in the same way with windows phone 7.

PhoneApplicationPage.OnNavigatedTo   - called before page displays
PhoneApplicationPage.OnNavigatedFrom - called before page is left.
When OnNavigatedTo is called the application may be coming from a close state if the application is just launched and this is the first page. A page earlier in the history stack(Previous Page), a page later in the history stack (Next page), A dormant state if the application is being reactivated or a tombstoned application also if the application is being reactivated. The OnNavigationFrom on the other hand may be called when the user navigates forward to another page, the user navigates back to the previous page by pressing the back button.
The application is going in a dormant mode, for example the user press the start button the application is going into a close state if the user press the back button and this page is the first page of our application. So as you can see, there are many scenarios to consider when deciding when to save and when to restore page state.

Fast Application Switching in Windows Phone

  • We’ll start by understanding how does fast application resume which is the HEART of the new release.
  • We’ll explore the execution model which features the fast resume (Dormant state)
  • We’ll look on how does Fast Application Switching affect our application when it comes to application life cycle

What is “Fast Application Switching”?

Microsoft’s platform in Windows Phone 7.5 is to provide a seamingless experience to the user. These are speed and responsiveness.

Most of the users do not just use a single application and use it on their smart
phones, most of them uses multiple applications and switches them back and forth.

Background processing must not affect the battery phone…

The phone should be smart enough to balance the overall system health and
capabilities and that is the reason why Microsoft release Mango release when 
it comes to multi tasking

The consequences..

Even in Mango update, the phone will only allow one application to run at any given time, any application that is no longer in the foreground is actually deactivated. In Windows Phone 7 execution model that is called tombstoning. For example, when the user closes the application by 
pressing the start button, the first application goes in tombstone mode. What does it mean? It means that the operating system saves the application state and dictionary state for later restores. It kills the threads and processes of the application. Now when the user goes back to the application using the hardware button
the OS will resuscitates the application back to the state it was in before being tombstoned. So we're like tricking the users that it is running in the background while in reality it is a brand new process that is being created upon activation and memory state has been restored from the saved state data.

The application lifecycle that Windows Phone 7 implements already addresses the two goals preventing the background processes from impacting the foreground and affecting the battery power. Now the problem is that it takes for a long time for an application to resume from a tombstone mode. If you already have a Windows Phone 7, you’ve probably experienced when you’re restoring your application that it is slow.

The solution

For the Windows Phone 7 developers you notice that there is a new state that has been added in the Application Life Cycle, which is the Dormant State, this is the new and enhanced model for Windows Phone 7.

What the Dormant State does is that it no longer kills the application's threads and processes instead the threads are not destroyed but halted and the application image is kept intact in memory. In other words, the application preserves the application instance if the application is reactivated it instantly resumes as if it is already loaded in the memory. So there is no need to go through to the process of restoring the application state from the saved dictionary as in the case of tombstoning that is what Fast Application Switching is. Also associated with Fast Application Switching is the new ability of the user to quickly jump across applications by pressing and holding the back button which will display the previous listed applications. Unfortunately, this feature is not yet available in the emulator.

So how does Mango Life Cycle works…?

Let’s say we have a running application and then the user presses the start or search button and then user launches a second application from the start menu, in Mango the effect of this action is for the first application to go to Dormant state, the process is not terminated but phone resources are detached and application threads and timers are suspended. The application goes into frozen state, it cannot execute code so it cannot consume battery power and it does not hold on to phone resources.

Before that happens, the deactivated event is raised by the platform and we can handle this event to save our own application data which needs to be saved so that if the application is later activated it will look to the user as if we continued the application running in the background. Now if the user navigates back to the application the activated event is first raised and then the application is fast resumed. Meaning, it restarts instantly as if there is no need for the OS to restore state into memory. Processes are already created, the frameworks are already initialized and application state and content are already present in the memory.

NOTE: While the application is in dormant state, if the user keeps launching new applications eventually the operating system will start running low in memory and it will start reclaiming some of the memory that is used by the dormant applications whose images are maintained and the OS does that by tombstoning dormant application as needed, starting with the one that are frozen first.

Again, tombstone mode means that the application threads are terminated although state dictionary are saved so the application can later be revived.  From there, if the user does return to the tombstone application then the observed behavior is the same as in Windows Phone 7 OS which is that the application will typically resume with the necessary delay to recreate threads and processes and restore state into memory. Note that the activated event is raised in the same way whether we are returning from a dormant state or the tombstone state. The alternative scenario is if the tombstoned app never gets reactivated, Mango will maintain state for a maximum of five (5) tombstoned applications beyond that or if the OS starts running low in memory the oldest tombstoned application will get terminated just like in WP7. So that is our basic deactivation pattern, to complete the lifecycle picture the user may of course choose to close the application while in the running application state by hitting the back button passed to the first page of our application. At this point, the closing event is raised and the application is terminated.

For completeness, the launching event is raised before the application event starts. So with this execution model, the typical scenario for the application that is being deactivated is for it to go to dormant state. If you’re familiar with the WP7 OS this is similar to the scenario where the user hits the starts button immediately followed by the back button to return to the application in which case no tombstoning occurs. While in Mango, deactivation without tombstoning is now the common case where in Phone 7 it used to be the exception.

How to build an application in Silverlight in Windows Phone 7


It’s day 2 of my post! Sorry for the very delayed post of my 7 day series of Windows Phone 7 due to busy week on developing an application in Windows Phone 7 and being invited to different schools for Windows Phone 7.

Now it’s day 2 of my introduction. As I normally say to my audience, Silverlight 4 is released last May 2010 but the framework that Windows Phone 7 will be using is only Silverlight 3. So when there is an instance that we want to use the features of Silverlight 4 like TextTrimming, well it’s not yet supported yet in WP7.

Silverlight 3 is the core framework for developing productivity tools, simple silverlight games, etc. It’s framework is purely based from Silverlight 3 framework but there were some enhancements for phone features of course. It’s good to learn Silverlight too when you are interested in developing further in Windows Phone 7 because you’re not only capable of developing applications in Web or Desktop but you also get to develop in the Mobile world! Learning Silverlight is easy! With the help of MSDN, MVP blogs, and PM Blogs you can easily have a jumpstart knowledge on how to develop your own Silverlight application. Silverlight API is so small compared to other frameworks that you Microsoft has. So starting as a Silverlight application will be a good start then advancing to other frameworks like WPF and ASP.NET.

Enough of the introduction. Let’s start the Silverlight tour in Windows Phone 7! Continue reading