Monday, January 12, 2015

Overview

A mobile app should aways keep track of the state. This means that if you write a message or complete a level it should be saved. The next time you go to that app, you should restart from where you left off. This feature is very easy to implement on the Windows Phone. More information can be found here.

Frame State

There are 2 very important methods to know about: OnLaunched and OnSuspending. We need to use SuspensionManager to save everything. If you used a BlankPage, you won’t have the SuspensionManager. Just create a BasicPage and it will prompt you to automatically create the some helped classes (including the SuspensionManager) for you.

Inside OnLaunched, we will add the following line of code.

1
ManagingState.Common.SuspensionManager.RegisterFrame(appFrame, "appFrame");

Results




In OnSuspending, we have to save the state.

1
2
// make sure you add async to the method signature
await ManagingState.Common.SuspensionManager.SaveAsync();

Results




We also need to restore our state, we do this again in OnLaunched. A bit lower than the code we wrote to register the frame, we will check if the app was terminated and restore the state if it was.

1
2
// make sure you add async to the method signature again
await ManagingState.Common.SuspensionManager.RestoreAsync();

Results




Application State

Above we saved what Frame or Page the user was on, but what if we want to store specific information that the user has entered? To accomplish this, we will use the local storage.

Save the state.

1
2
Windows.Storage.ApplicationDataContainer localStorage = Windows.Storage.ApplicationData.Current.LocalSettings;
localStorage.Values["someKey"] = "I'm saving this text for later";

Restore the state in NavigationHelper_LoadState (it will be there if you chose BasicPage).

1
2
3
4
5
6
// Again we get the storage
Windows.Storage.ApplicationDataContainer localStorage = Windows.Storage.ApplicationData.Current.LocalSettings;

if ( localStorage.Values.ContainsKey("someKey") ) {
  myLocalVariable = localStorage.Values["someKey"].toString();
}




The other way to save Application state (which is much easier) is with NavigationHelper_SaveState and NavigationHelper_LoadState.

Save State.

1
e.PageState["someKey"] = "I'm saving this text for later";

Results

Load State.

1
2
3
if ( e.PageState != null && e.PageState.ContainsKey("someKey") ) {
  myLocalVariable = e.PageState["someKey"].toString();
}

Results


Random Posts