|
原文地址:http://www.jeffblankenburg.com/post/31-Days-of-Windows-Phone-7c-Day-14-Tombstoning-(Multi-tasking).aspx
本文讨论在Windows phone 7 中最富有正义的主题:多任务
很多文章说Windows phone 7不好的地方,第一个就是缺乏多任务。
Windows phone 7 有多任务
是的,我这样说。我这样说是因为他是真实存在的。Windows phone7 是一个能运行多任务的手机,在我上网的时候听音乐,玩游戏的时候接收邮件。然而让我们误解的是,作为程序开发者我们不让程序在后台运行。
在windows phone 7工作的几个月,我只有两个原因需要程序后台运行:
1 应用播放音乐。
2 需要从传感器上接收数据。
除了上边两个原因,我没有让程序后台运行的需要。
你也许会说我希望程序接收网络的更新,难道我不需要后台运行吗?我的回答是不,你不需要。有一种机制叫做推送提醒将会在以后说道,他是专门解决这个问题的。
对于我们,微软给了一种叫做“墓碑”的机制放置程序一直运行,及时我们的进程被杀死。下面是快速图解:
从上图中可以看出,有挂起和激活两种状态,分别对应用户进入以及推出程序。通过这些事件,我们可以让用户觉得程序未曾停止过。当我们添加了独立存储,以及推送通知,将会更加给力。
假装多任务
在你的App.xaml中有内置的方法,下面是默认状态:
// 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)
{
}
luanching以及closing方法在传统案例中被用到:通过传统方式开始以及离开程序。Activated和Deactivated方法是非正式进入以及离开。例如,使用了返回按钮回到程序或是接电话离开程序。这是非正常的方式,我强烈建议你测试这些情况。
你有两种方式存储用户状态,并且在用户回来以后刷新状态,造成的假象就是他们未曾离开过。原因很简单:
1 很多用户离开程序的时候并不意识到他依旧在占用系统资源,在背后消耗电池。
2 很懂程序不需要后台运行。有更好的方式使用资源。
保存状态到设备上
用户离开以后我们要做的第一件事是保存用户信息。在我的示例程序中,我们将会创建一个计时器运行,及时他实际上不再运行。
为了保存数据,我将会使用PhoneApplicationSerive。我将会涉及到独立存储的东西,这是一种保存数据的持久方式在示例中,我希望你知道离开程序的时间,这样我能够知道离开以及再次进入的间隔:
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
PhoneApplicationService.Current.State["LeftTime"] = DateTime.Now;
}
我使用了OnNavigatedTo事件来处理页面加载。如果“LeftTime”存在,我将使用它,否则我认为你是第一次使用程序。
在激活时重现状态
以下示例保存我离开的时间:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (PhoneApplicationService.Current.State.ContainsKey("LeftTime"))
{
DateTime deactivated = (DateTime)PhoneApplicationService.Current.State["LeftTime"];
secondsSinceStart = (int)(DateTime.Now - deactivated).TotalSeconds + (int)PhoneApplicationService.Current.State["ElapsedTime"];
writeTime();
writeDate();
timer.Start();
}
else secondsSinceStart = 0;
}
使用这个方法,我将会保持一个持续运行的计时器,及时当用户离开。如果你问用户,他们会说程序移植在运行。唯一的不同是你的程序运行太慢将会出现一个“恢复中”的画面。
这就是墓碑机制背后的故事。保存你的用户数据,然后再恢复他。你的用户不知道什么差别,除了你给予他们更多的电量、程序运行状态以及用户体验。 |
|