In .NET Rocks! Show number 578 about the Silverlight Pivot Viewer, a listener writes in about the lack of multitasking in Windows Phone 7.
He points out that he often uses a stopwatch on Android and let it “run in the background” while doing other tasks.
This is a perfect example of something that is entirely possible on WP7 if you try to change your mindset and look at what’s possible instead of focusing on limitations.
To prove my point, I created a (from the users point of view) multitasking stopwatch for WP7:
Also, read my general post about Windows Phone 7 multitasking.
What actually happens here is that I cheat and use the WP7 lifecycle events. When the user navigates away from my app, the Application_Deactivated event is fired and I create a tombstone for my application with the start time (when the user pressed start on the stopwatch).
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
if(true==PhoneApplicationService.Current.State.ContainsKey(StartTimeKey))
{
PhoneApplicationService.Current.State.Remove(StartTimeKey);
}
if(StartTime!=null) PhoneApplicationService.Current.State.Add(StartTimeKey,StartTime);
}
When the user presses the Back button, the application is reactivated and is actually started back up, but because a tombstone exists, the Application_Activated event is fired, and I get my start time back.
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if(PhoneApplicationService.Current.State.ContainsKey(StartTimeKey))
{
StartTime = PhoneApplicationService.Current.State[StartTimeKey] as DateTime?;
}
}
If I get a start time, I will auto-start the timer that controls the display and start counting up from the original start-time.
To the user, this is a multitasking stopwatch!
To the developer, sure it’s a little work to shut down and start back up. But the advantage is that I know I always have the full power of the phone hardware when MY app is running.
Source code: Wp7StopWatch.zip (78.86 kb)
Tags: wp7, silverlight, windows phone, multitasking