if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
SuspensionDemo.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
在OnSuspending 方法中,使用SuspensionManager.SaveAsync 方法将挂起应用的当前状态进行保存,这里可以调用异步操作来进行处理。
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
await SuspensionDemo.Common.SuspensionManager.SaveAsync();
deferral.Complete();
}
注册完成后,打开MainPage.xaml.cs 在SaveState 方法中添加如下代码,使应用挂起时能将Name 字段保存起来。
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first
rootFrame = new Frame();
SuspensionDemo.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
await SuspensionDemo.Common.SuspensionManager.RestoreAsync();
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
最后,在MainPage.xaml.cs 的LoadState 方法中将pageState的Name 字段内容恢复即可。我们再次F5运行应用;录入姓名;挂起并终止应用,应用恢复后可以看到之前录入的姓名仍然存在。