Windows Phone: implementing fast app switching (needed for DVLUP!)

Since my last post talked about making a Live Tile update, which is needed for the DVLUP challenges, I thought I’d talk about a different requirement – Fast App Switching.

The key to implementing Fast App Switching is understanding the lifecycle of an app. The MSDN page on App activation and deactivation for Windows Phone is an excellent guide, and I refer to it often. The table at the bottom of the page is a quick guide to what you need to do to support app suspend/resume, including Fast App Switching.

Here’s a quick example in code. Let’s assume the MainPage just has one TextBox on it whose contents we want to preserve if the user switches away from the app.


// a bunch of code omitted
public partial class MainPage : PhoneApplicationPage {
private bool _isNewPageInstance = false;

public MainPage()
{
InitializeComponent();
_isNewPageInstance = true;
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
base.OnNavigatedTo(e);
if (_isNewPageInstance)
{
if (State.Count > 0)
{
// this assumes you always save everything
// if not, check with State.ContainsKey()
myTextBox.Text = State["TextBoxContents"] as string;
}
}
}

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) {
base.OnNavigatedFrom(e);
if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
{
// save state for all controls
State["TextBoxContents"] = myTextBox.Text;
} else {
// navigating back, so don't save any state
State.Clear();
}
}
}

If you have any state that you want to persist throughout the app, you can do a similar thing with PhoneApplicationService.State, and listening in the PhoneApplicationService.Activated and PhoneApplicationService.Deactivated events.

It’s easy to test the case when your app gets deactivated and quickly reactivated (just press the start button, then hold the back button and switch back to it), but testing the tombstoned case is important too. To test this, in the project settings under “Debug”, there’s a checkbox called “Tombstone upon deactivation while debugging” – just turn that on, debug the app, and switch away and switch back. You may uncover all kinds of bugs 🙂

See all my Windows Phone development posts.

I’m planning on writing more posts about Windows Phone development – what would you like to hear about? Reply here, on twitter at @gregstoll, or by email at greg@gregstoll.com.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s