Windows 8 应用开发 - 挂起与恢复

     Windows 8 应用一般涉及到两种数据类型:应用数据与会话数据。在上一篇提到的本地数据存储就是应用层面的数据,包括应用参数设置、用户重要数据等。那么会话层面的数据是基于用户每次使用应用而造成,这些数据可能不须要留存在设备中。在整个应用生命周期中,应用启动后便进入运行状态。当用户离开或系统进入待机状态时,应用会进入挂起状态,此时应用将被放入到内存中,待用户从新使用时便会恢复成运行状态。html

IC576232

     在这个过程当中用户以前可能已经录入了一些数据,而且但愿在应用恢复时能够继续进行录入。对于开发者来讲,咱们须要在应用挂起时将一些会话数据进行保存,当应用恢复后同时将暂存数据复原,以便让用户继续使用。须要注意的是MSDN中提到:“当用户经过按 Alt+F4 或使用关闭手势关闭应用时,应用将被挂起 10 秒钟而后被终止。”也就意味着关闭的应用只有10秒钟时间能够被恢复。下面将经过实例进行演示,首先建立一个Textbox 让用户录入名字进行会话操做。咱们首先来尝试一下没有进行挂起暂存处理的应用是何种结果。windows

<StackPanel Grid.Row="1" Margin="120,30,0,0">      <StackPanel Orientation="Horizontal" Margin="0,20,0,20">          <TextBlock Text="Name: " Style="{StaticResource BasicTextStyle}" Width="50"/>          <TextBox x:Name="nameInput" Width="200"/>      </StackPanel>  </StackPanel>

挂起

     直接按F5运行应用,在Name 栏中输入名字或任意字符。在VS2012的Debug Location 工具栏能够看到挂起(Suspend )的选项,咱们选择挂起并终止(Suspend and shutdown),程序挂起后从系统左侧菜单栏里找到以前的应用从新启用,恢复后的应用Name 栏中的文字已经丢失。对于名字这样的简单录入还能够接受,若是录入项较多的话那将损失惨重。app

image

     接下来咱们将进行应用挂起处理,打开App.xaml.cs 程序,在OnLaunched 方法中建立了rootFrame,当rootFrame 为Null 时将从新建立Frame,在这个逻辑判断中要使用SuspensionManager.RegisterFrame 方法进行rootFrame 注册,这样才可使应用得到根Frame 信息并进行数据存储。异步

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 方法将挂起应用的当前状态进行保存,这里能够调用异步操做来进行处理。async

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 字段保存起来。ide

protected override void SaveState(Dictionary<String, Object> pageState)  {      pageState["name"] = nameInput.Text;  }

恢复

     挂起操做完成后,就要进行恢复操做,将暂存的数据恢复到应用中。再次打开App.xaml.cs 在PreviousExecutionState 判断为Terminated 时加入SuspensionManager.RestoreAsync 方法恢复之前的应用状态。工具

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运行应用;录入姓名;挂起并终止应用,应用恢复后能够看到以前录入的姓名仍然存在。ui

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)  {      if (pageState != null && pageState.ContainsKey("name"))      {          nameInput.Text = pageState["name"].ToString();      }  }

×××

http://sdrv.ms/U1zyQdspa

相关文章
相关标签/搜索