Windows Phone: implementing fast app switching (needed for DVLUP!)
Mood: tired
Posted on 2012-12-10 23:30:00
Tags: windowsphone wpdev
Words: 348
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();
}
}
}
This backup was done by LJBackup.