应用程序生命周期(墓碑机制(程序和页面))【WP7学习札记之十一】

      由于Windows Phone 目前不支持第三方应用程序在后台运行,也就是说只有唯一一个第三方应用程序在前台运行,当用户离开应用程序页面时,应用程序会被操作系统终止(推送通知服务将在后面讲)。微软提供了另一种方法称之为tombstone,虽然在Mango更新中支持了所谓的“多任务”,但是我们还是需要处理墓碑化,在CodePlex就有这么一个开源项目,TombStoneHelper,可以帮助我们简化墓碑操作,但是我们首先来系统学习下墓碑机制以及应用程序生命周期。

      首先我们需要认识清什么是墓碑机制以及楚一般的应用程序生命周期和TombStone生命周期有什么区别。

tombstone是一个很形象的描述,Imaging this:操作系统对应用程序说,你要死了,你有什么东西赶紧记下来写在你的墓碑上吧~(10秒钟原则

    在WP7中用户在应用程序主界面点击Back按钮,和通常我们在WinForm程序中点击“关闭”按钮是一样的,结果都是退出应用程序。

生命周期处理事件,在App.xaml.cs中的英文描述是这样子的:

        // Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}

// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}

// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}

// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}

翻译过来总结下就是:

分别介绍下,Launching事件:当应用程序启动时候调用,重新激活时不调用;通常用来加载应用程序的一些永久配置数据。

Closing事件:当应用程序关闭的时候调用,失去激活的时候不调用;通常用来保存一些应用程序永久配置数据到独立存储空间中。

 Activated事件:当程序重新激活的时候调用,启动的时候不调用;从PhoneApplicationService.State["key"]中读取一些应用程序临时数据。

Deactived事件:当程序失去激活的时候调用,关闭的时候不调用;通常用来使用PhoneApplicationService.State保存一些应用程序临时数据。

 我们不应该在以上几个事件中处理大量的数据,因为MS有一个称之为10秒钟原则的限制(为了更好的用户体验,超过10秒,用户会想可能程序出问题了~)。

前面的一直说的是程序的相关信息,而当程序被重新激活的时候,我们需要回复页面原来的显示状态。通过PhoneApplicationPage.State(注意啊,前面的是PhoneApplicationService.State)在离开页面和进入页面的时候保存和回复页面的显示状态信息。

离开页面的时候,PhoneApplicationPage.State["key"]保存界面的显示状态。

当进入页面的时候,PhoneApplicationPage.State["key"]恢复页面的额显示状态。

结束语:本文讲述了应用程序生命周期,Tombstone墓碑机制,以及10秒钟原则,如何保存和恢复应用程序的永久数据(独立存储IsolatedStorage),如何保存和恢复应用程序的临时数据(PhoneApplicationService.State["key"]),如何保存和恢复页面的显示状态(PhoneApplicationPage.State["key"])。

 

 具体请参见MSDN:Windows Phone 执行模型http://msdn.microsoft.com/zh-cn/library/ff769557(v=vs.92).aspx

Windows Phone 执行模型

此主题尚未评级 评价此主题
 
Windows Phone
 

 

2012/2/9

在 Windows Phone 执行模型下,当用户导航离开应用程序时,该应用程序通常会置于休眠状态。但是,当应用程序处于此睡眠状态时,操作系统可能会将其终止。本节介绍如何构建在此模型下提供无缝用户体验的应用程序。

posted @ 2012-03-13 17:02  DebugLZQ  阅读(1021)  评论(2编辑  收藏  举报