Windows 8 應用開發 - 掛起與恢復


     Windows 8 應用通常涉及到兩種數據類型:應用數據與會話數據。在上一篇提到的本地數據存儲就是應用層面的數據,包括應用參數設置、用戶重要數據等。那么會話層面的數據是基於用戶每次使用應用而形成,這些數據可能不需要留存在設備中。在整個應用生命周期中,應用啟動后便進入運行狀態。當用戶離開或系統進入待機狀態時,應用會進入掛起狀態,此時應用將被放入到內存中,待用戶重新使用時便會恢復成運行狀態。

IC576232

     在這個過程中用戶之前可能已經錄入了一些數據,並且希望在應用恢復時可以繼續進行錄入。對於開發者來說,我們需要在應用掛起時將一些會話數據進行保存,當應用恢復后同時將暫存數據復原,以便讓用戶繼續使用。需要注意的是MSDN中提到:“當用戶通過按 Alt+F4 或使用關閉手勢關閉應用時,應用將被掛起 10 秒鍾然后被終止。”也就意味着關閉的應用只有10秒鍾時間可以被恢復。下面將通過實例進行演示,首先創建一個Textbox 讓用戶錄入名字進行會話操作。我們首先來嘗試一下沒有進行掛起暫存處理的應用是何種結果。

<StackPanel Grid.Row="1" Margin="120,30,0,0">
    <StackPanel Orientation="Horizontal" Margin="0,20,0,20">
        <TextBlock Text="Name: " Style="{StaticResource BasicTextStyle}" Width="50"/>
        <TextBox x:Name="nameInput" Width="200"/>
    </StackPanel>
</StackPanel>

掛起

     直接按F5運行應用,在Name 欄中輸入名字或任意字符。在VS2012的Debug Location 工具欄可以看到掛起(Suspend )的選項,我們選擇掛起並終止(Suspend and shutdown),程序掛起后從系統左側菜單欄里找到之前的應用重新啟用,恢復后的應用Name 欄中的文字已經丟失。對於名字這樣的簡單錄入還可以接受,如果錄入項較多的話那將損失慘重。

image

     接下來我們將進行應用掛起處理,打開App.xaml.cs 程序,在OnLaunched 方法中創建了rootFrame,當rootFrame 為Null 時將重新創建Frame,在這個邏輯判斷中要使用SuspensionManager.RegisterFrame 方法進行rootFrame 注冊,這樣才可以使應用獲得根Frame 信息並進行數據存儲。

if (rootFrame == null)
{
    // Create a Frame to act as the navigation context and navigate to the first page
    rootFrame = new Frame();

    SuspensionDemo.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");

    if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
    {
        //TODO: Load state from previously suspended application
    }

    // Place the frame in the current Window
    Window.Current.Content = rootFrame;
}

     在OnSuspending 方法中,使用SuspensionManager.SaveAsync 方法將掛起應用的當前狀態進行保存,這里可以調用異步操作來進行處理。

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //TODO: Save application state and stop any background activity
    await SuspensionDemo.Common.SuspensionManager.SaveAsync();
    deferral.Complete();
}

     注冊完成后,打開MainPage.xaml.cs 在SaveState 方法中添加如下代碼,使應用掛起時能將Name 字段保存起來。

protected override void SaveState(Dictionary<String, Object> pageState)
{
    pageState["name"] = nameInput.Text;
}

恢復

     掛起操作完成后,就要進行恢復操作,將暫存的數據恢復到應用中。再次打開App.xaml.cs 在PreviousExecutionState 判斷為Terminated 時加入SuspensionManager.RestoreAsync 方法恢復以前的應用狀態。

protected async override void OnLaunched(LaunchActivatedEventArgs args)
{

    Frame rootFrame = Window.Current.Content as Frame;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first
        rootFrame = new Frame();
        
        SuspensionDemo.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");
        
        if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
            await SuspensionDemo.Common.SuspensionManager.RestoreAsync();
        }

        // Place the frame in the current Window
        Window.Current.Content = rootFrame;
    }

    if (rootFrame.Content == null)
    {
        // When the navigation stack isn't restored navigate to the first page,
        // configuring the new page by passing required information as a navigation
        // parameter
        if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
        {
            throw new Exception("Failed to create initial page");
        }
    }
    // Ensure the current window is active
    Window.Current.Activate();
}

     最后,在MainPage.xaml.cs 的LoadState 方法中將pageState的Name 字段內容恢復即可。我們再次F5運行應用;錄入姓名;掛起並終止應用,應用恢復后可以看到之前錄入的姓名仍然存在。

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
    if (pageState != null && pageState.ContainsKey("name"))
    {
        nameInput.Text = pageState["name"].ToString();
    }
}

源碼下載

http://sdrv.ms/U1zyQd


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM