本文共 2821 字,大约阅读时间需要 9 分钟。
我们知道,程序可能有活跃,扶起,激活,终止等状态。
这里主要讲的是当用户切出应用又切回来时需要特别地做的一些处理, 与wp7相同,例如:
微软有一些用户体验的指导方针:
1、当程序激活时我们需要做什么
重写OnLaunched事件
using System;using Windows.ApplicationModel;using Windows.ApplicationModel.Activation;using Windows.UI.Xaml;namespace AppName{ public partial class App { async protected override void OnLaunched(LaunchActivatedEventArgs args) { EnsurePageCreatedAndActivate(); } // Creates the MainPage if it isn't already created. Also activates // the window so it takes foreground and input focus. private MainPage EnsurePageCreatedAndActivate() { if (Window.Current.Content == null) { Window.Current.Content = new MainPage(); } Window.Current.Activate(); return Window.Current.Content as MainPage; } }}
恢复数据
async protected override void OnLaunched(LaunchActivatedEventArgs args){ if (args.PreviousExecutionState == ApplicationExecutionState.Terminated || args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser) { // TODO: Populate the UI with the previously saved application data } else { // TODO: Populate the UI with defaults } EnsurePageCreatedAndActivate();}
如果程序是非法终止的,即是状态是 NotRunning, 那就没有数据可以恢复。
2、当程序挂起时我们需要做什么
首先订阅suspending事件
using System;using Windows.ApplicationModel;using Windows.ApplicationModel.Activation;using Windows.UI.Xaml;partial class MainPage{ public MainPage() { InitializeComponent(); App.Current.Suspending += new SuspendingEventHandler(App_Suspending); }}
然后保存用户数据
CoreDispatcher dispatcher = Window.Current.Dispatcher;private void App_Suspending(object sender, object e){ // This is a good time to save app data in case the process gets terminated. IPropertySet settingsValues = ApplicationData.Current.LocalSettings.Values; // TODO: Save the app data}
当程序挂起时数据会保存在内存,但是当系统资源不够用时系统会终止程序,所以当我们重新启动程序时,系统会触发Activated事件,我们需要在OnLanuched方法中恢复上次挂起时保存的数据。系统并不会通知我们何时终止了程序, 所以我们必须得在挂起时保存数据以保证在重新启动终止的程序时能恢复数据。
3、当程序恢复时我们需要做什么
首先订阅Resuming事件
partial class MainPage{ public MainPage() { InitializeComponent(); App.Current.Resuming += new Windows.UI.Xaml.EventHandler(App_Resuming); }}
更新UI可能产生的新数据
CoreDispatcher dispatcher = Window.Current.Dispatcher;private void App_Resuming(object sender, object e){ // There are no special arguments for the resuming event dispatcher.Invoke(CoreDispatcherPriority.Normal, (object invokedSender, InvokedHandlerArgs invokedArgs) => { // TODO: Refresh network data }, this, null);}
如果没有数据要更新,则不需要订阅此事件。
转载地址:http://folgb.baihongyu.com/