今天為大家介紹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事件