沈阳格力专卖店 发表于 2015-5-22 09:37:38

Windows 8 系列(二):Metro Style 应用程序生命周期(Metro Style Application Life Cycle)

  今天为大家介绍Windows 8 Metro Style 应用程序的生命周期。Windows 8 Metro Style 应用程序与Windows Phone应用程序同宗同源,所以应用程序的生命周期也是大同小异,首先我们来看看windows phone 7应用程序的生命周期
  
  

  
  
  简要一点就是:启动程序--〉程序运行--〉 休眠 (可选)--〉 墓碑(可选) --〉 关闭
  
  与Windows Phone相似,windows 8 Metro Style 应用程序的生命周期如下图所示:
  

  
  这个是windows 8 developer preview 版本的Metro Style生命周期,目前Windows 8 Beta版本的,在此基础上增加了用户结束应用程序,即:Running app ---(User Terminate)---> ClosedByUser。
  如果你对Windows 8 Metro Style 应用程序有所了解的话,就会发现系统没有提供给用户这样的功能,而我们的Metro Style 应用程序的设计规范里又不允许我们设置退出或者关闭功能(像Windows 7中的右上角的"X" ),那我们如何手动关闭Metro Style应用程序呢??
  还记得我们在玩一些客户端小游戏时用快捷键“Alt + F4” 退出游戏吗?对,我们就是用这个快捷键,可以手动关闭应用程序。



protected override void OnLaunched(LaunchActivatedEventArgs args)
      {
            // TODO: Create a data model appropriate for your problem domain to replace the sample data
            var sampleData = new SampleDataSource();
            if (args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
            {
                //TODO: Load state from previously suspended application
            }
            // Create a Frame to act navigation context and navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            var rootFrame = new Frame();
            rootFrame.Navigate(typeof(GroupedItemsPage), sampleData.ItemGroups);
            // Place the frame in the current Window and ensure that it is active
            Window.Current.Content = rootFrame;
            Window.Current.Activate();
      }
  从上面的代码中可以看到,在应用程序再次被启动时,OnLaunched事件参数中可以得到一个ApplicationExecutionState枚举类型,从中可以得到应用程序在这之前是什么状态。
  此枚举类型的详细内容:



namespace Windows.ApplicationModel.Activation
{
    // Summary:
    //   Specifies the current execution state of the app.
    public enum ApplicationExecutionState
    {
      // Summary:
      //   The app is not running.
      NotRunning = 0,
      //
      // Summary:
      //   The app is running.
      Running = 1,
      //
      // Summary:
      //   The app is suspended.
      Suspended = 2,
      //
      // Summary:
      //   The app was terminated after being suspended.
      Terminated = 3,
      //
      // Summary:
      //   The app was closed by the user.
      ClosedByUser = 4,
    }
}
  
  以上只是自己的一点心得,如果有什么意见和建议,欢迎大家提出。
  同时欢迎大家跟我一起探讨,我们一起进步。

  
  多谢jesse hao的提醒,我把第一张图加了一部分,程序在休眠的时候也是会触发OnNavigatedFrom事件
页: [1]
查看完整版本: Windows 8 系列(二):Metro Style 应用程序生命周期(Metro Style Application Life Cycle)