Windows 8 Application Development-pending and restoring

Source: Internet
Author: User

Windows 8 applications usually involve two data types: Application Data and session data. The local data storage mentioned in the previous article is the data at the application layer, including application parameter settings and important user data. The session-layer data is generated based on the user's use of the application each time. The data may not need to be stored on the device. During the entire application lifecycle, the application enters the running state after it is started. When the user leaves or the system enters the STANDBY state, the application will be suspended, and the application will be put into the memory. When the user re-uses the application, it will return to the running state.

In this process, you may have already entered some data and want to continue inputting data when the application recovers. For developers, we need to save some session data when the application is suspended. After the application is restored, the temporary data will be restored so that users can continue to use the data. It should be noted that, as mentioned in MSDN, "when you close an application by pressing Alt + F4 or using the close gesture, the application will be suspended for 10 seconds and then terminated ." This means that the disabled application can be restored in 10 seconds. The following example shows how to create a Textbox for the user to enter a name for the session operation. First, let's try out the result of an application that has not been suspended for temporary storage.

<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>
Pending

Press F5 to run the application and enter the Name or any character in the Name column. You can see the Suspend option in the Debug Location Toolbar of VS2012. We choose to Suspend and stop (Suspend and shutdown ), after the application is suspended, find the previous application re-enable from the left-side menu bar of the system, and the text in the restored application Name bar is lost. Simple input such as name is acceptable. If there are many input items, the loss will be high.

Next, we will suspend the application and open the App. xaml. cs program. A rootFrame is created in the OnLaunched method. When the rootFrame is Null, the Frame is re-created. In this logic judgment, SuspensionManager is used. the RegisterFrame method registers rootFrame so that the application can obtain the root Frame information and store the data.

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;}

In the OnSuspending method, use the SuspensionManager. SaveAsync method to save the current state of the suspended application. asynchronous operations can be called here for processing.

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();}

After registration, open MainPage. xaml. cs and add the following code to the SaveState method to save the Name field when the application is suspended.

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

After the pending operation is complete, restore the temporary data to the application. Open App. xaml. cs again and add the SuspensionManager. RestoreAsync method when the previusexecutionstate is determined to be Terminated to restore the previous application status.

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();}

Finally, restore the Name field of pageState in the LoadState method of MainPage. xaml. cs. Let's run the application in F5 again; enter the name; suspend and terminate the application. After the application is restored, we can see that the previously entered name still exists.

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

Http://sdrv.ms/U1zyQd

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.