by October 7, 2010 0 comments



Last month we introduced the upcoming Windows Phone 7 (WP7) and its development platform and also wrote a quick, small sample application using the tools to see how easy it actually is. In this part of the series, you’ll get an introduction to the application lifecycle of apps in the platform. Interestingly, although the previous Windows Mobile platform supported full multitasking, WP7 runs only one 3rd party application at a time. However, it is easy enough to simulate a multitasking approach for your application by understanding what happens when it is executed.

If your application on the phone is not running and the user taps on its icon in the app list, it is launched for the first time. The app behaves as you would want it to as long as you are in it. Now there are two ways that you can “switch” to another app on the phone. The first is to click the”<--" (back) button on the phone. If you're in your application and have gone through multiple screens (called pages — but they're not Web but Silverlight) in it, you are brought back step-by-step — exactly as in the case of a Web browser. However, once you reach the very first page of your application, it exits the app itself — basically closing it.

img border=”0″ src=”/2010/images/developer_img6.jpg” align=”right” hspace=”4″ vspace=”4″ width=”550″ height=”202″>

The other way is to click on the Windows button on the phone. When this happens, your app is deactivated — that is, the running application is terminated (quite ruthlessly) and the you are returned to the phone’s Home screen. You can now start a new app from here. But it also does one other thing — it keeps a reference (called a scary sounding Tombstone) inthe phone’s back-stack. The tombstoning or deactivating of the application allows the user to return to it by pressing the back key.

To understand how this works, take a look at the following ­scenario:
1. User clicks on an app on the phone
2. The app is launched and theuser can interact with it
3. The user clicks the Windows button on the phone
4. The app is deactivated with a tombstone in the back-stack
5. The user clicks on another app in the phone
6. That app is launched
7. The user interacts with it and then clicks the Back button on the phone
8. This second app is closed and the user returned to the Home screen.
9. The user now clicks the Back button again
10. Since the 1st app’s tombstone is sitting in the back-stack, the app is activated and user returned to it.

You might wonder why has this been done rather than giving true multitasking which earlier WM platforms had. The answer is that it is better to run a single app for preserving battery life. Since only one app can run, background processing cannot drink up the battery power at a high rate. And don’t worry, there are ways that you can still get notification and other services instead of something running in the background.

Code sample
Let’s write some code to understand this. Fire up VS2010 with the WP7 tools installed. Create a new “Windows Phone Application” project. When the designer comes up, change the ApplicationTitle and PageTitle to something appropriate. Drop in a Button control from the Toolbox and change its Content property to say “About…”.Double click the button in the designer to open its click event and enter the following code:

NavigationService.Navigate(new Uri(“/about.xaml”, UriKind.Relative));
Now right click the solution and select “Add | New Item” and then choose the “Windows Phone Portrait Page”. Name the page “About.xaml”. When the designer for this new page loads, again change the page title and add a TextBlock control to the content area and type in some text there. Notice that in the Solution Explorer there is a file already there called “App.xaml”. Open it up to view the markup and then open up its code file — App.xaml.cs. Here you will note that there are 4 application level event handlers already setup. These correspond to the 4 application launch and exit events that we discussed above — launching, closing, ­activated and deactivated.
Let’s write some code that will demonstrate this application lifecycle clearly. In each of the event handlers write the following code (make sure to replace the string in each with the correct event information — that is closing, activated or deactivated.)
Debug.WriteLine(“*** APP LAUNCHING EVENT FIRED ***”);
Hit F5 to start up the WP7 emulator and deploy and debug the app on it. If you have the Output window open in VS2010, you will see the app launching message showing up. You can press the button to go to the about page. Click the Windows button on the emulator. You will see that you are returned to the Home screen and the Output window shows the deactivation message. You are also shown that the app being debugged has exited — which is why VS2010 also stops the debug mode.
At this point if you click the Back button, the app reference (tombstone) in the emulator will be retrieved from the back-stack and the application will be activated to the correct 2nd page. However to see the message in VS2010 Output window, you will need to quickly press F5 again to re-attach the debugger to the process in the emulator. Now click the Back button and this time you will get the closing message as well as a complete exit. If you click Back again nothing will happen since your app’s tombstone is no longer there.

Managing state
This is all simple enough. But it is important to note one major issue — when the application terminates (either by deactivating or closing) any data in the application is not saved automatically. This can be easily demonstrated as follows. In the About.xaml page, simply add a TextBox control to the page and call it txtFeedback. Now re-deploy the app to the emulator, run the app and go to the about page. Enter some text using the on screen keyboard. Click the Windows key to exit the app and then the Back key to return to it. You’ll be correctly brought back to the 2nd page — but the text you entered would have vanished. So how do you solve this?
There are two ways of taking care of this depending on the data type or importance. Data that is to be stored permanently or between app and device restarts are called “persistent data”. We’ll look at this in a future article when it comes to saving and retrieving data. The other type of data is called “transient data” and is meant for specific instances of the application. This type will not survive a device restart but will work across app restarts (through launching or activating).
For this to work, open up the About.xaml.cs file and add two new page level event handlers and a using statement for ­Microsoft.Phone.Shell. The first, OnNavigatedFrom works whenever the user navigates away from that particular page — whether within the app itself or by clicking the back or Windows key. It uses an object called the PhoneApplicationService “State” to store this transient data as a dictionary key-value pair like this:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    
Debug.WriteLine(“— Navigated FROM about page —“);
    
if (PhoneApplicationService.Current.State.ContainsKey(“FEEDBACK”))
        
PhoneApplicationService.Current.State.Remove(“FEEDBACK”);
    
PhoneApplicationService.Current.State.Add(“FEEDBACK”, txtFeedback.Text);}
As you can see, this code will run whenever the user navigates away from the about page. It first checks if the State dictionary already has a feedback value and removes it if it finds it. It then adds the current text entered into the state dictionary.
The OnNavigatedTo event does the opposite —whenever the page is visited, it is fired. So all we need to do is check within the state and retrieve the value and populate the controls.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    
Debug.WriteLine(“— Navigated TO about page —“);
    
if (PhoneApplicationService.Current.State.ContainsKey(“FEEDBACK”))
    
{
        
string fb = PhoneApplicationService.Current.State[“FEEDBACK”] as string; if (!String.IsNullOrEmpty(fb))
            
txtFeedback.Text = fb;
    
}}
Now try the same exercise as before. You will see that when you reactivate the application, this time the text in the feedback field is not lost. You will also see the navigation (from and to) messages in the Output window in VS2010.

Related Articles:

Win Phone 7: Data Binding & Storing Persistent Data Writing code

Developing Windows Phone 7 Application

No Comments so far

Jump into a conversation

No Comments Yet!

You can be the one to start a conversation.

Your data will be safe!Your e-mail address will not be published. Also other data will not be shared with third person.