处理应用恢复

重要的 API

了解当系统恢复你的应用时刷新 UI 的情况。 本主题中的示例可向事件处理程序注册 Resuming 事件。

注册恢复事件处理程序

注册以处理 Resuming 事件,该事件指示用户从你的应用切换到桌面或其他应用,而后又切换回你的应用。

partial class MainPage
{
   public MainPage()
   {
      InitializeComponent();
      Application.Current.Resuming += new EventHandler<Object>(App_Resuming);
   }
}
Public NonInheritable Class MainPage

   Public Sub New()
      InitializeComponent()
      AddHandler Application.Current.Resuming, AddressOf App_Resuming
   End Sub

End Class
MainPage::MainPage()
{
    InitializeComponent();
    Windows::UI::Xaml::Application::Current().Resuming({ this, &MainPage::App_Resuming });
}
MainPage::MainPage()
{
    InitializeComponent();
    Application::Current->Resuming +=
        ref new EventHandler<Platform::Object^>(this, &MainPage::App_Resuming);
}

刷新显示的内容并重新获取资源

在用户切换到其他应用或桌面后,系统会暂停你的应用数秒钟。 每当用户切换回你的应用时,系统会恢复你的应用。 当系统恢复你的应用时,你的变量和数据结构的内容与系统将你的应用暂停之前的内容相同。 系统将还原离开时所使用的应用。 对用户来说,就好像应用一直在后台运行一样。

当应用处理 恢复 事件时,应用可能已暂停数小时或数天。 它应该在应用处于暂停状态时刷新可能已过时的任何内容,例如新闻源或用户位置。

此时,还可以还原你在应用处于暂停状态时发布的任何独占资源,例如文件句柄、相机、I/O 设备、外部设备和网络资源。

partial class MainPage
{
    private void App_Resuming(Object sender, Object e)
    {
        // TODO: Refresh network data, perform UI updates, and reacquire resources like cameras, I/O devices, etc.
    }
}
Public NonInheritable Class MainPage

    Private Sub App_Resuming(sender As Object, e As Object)
 
        ' TODO: Refresh network data, perform UI updates, and reacquire resources like cameras, I/O devices, etc.

    End Sub
>
End Class
void MainPage::App_Resuming(
    Windows::Foundation::IInspectable const& /* sender */,
    Windows::Foundation::IInspectable const& /* e */)
{
    // TODO: Refresh network data, perform UI updates, and reacquire resources like cameras, I/O devices, etc.
}
void MainPage::App_Resuming(Object^ sender, Object^ e)
{
    // TODO: Refresh network data, perform UI updates, and reacquire resources like cameras, I/O devices, etc.
}

注意

由于 Resuming 事件未从 UI 线程中引发,因此必须在你的处理程序中使用调度程序,调度对你的 UI 的任何调用。

注解

当你的应用连接到 Visual Studio 调试器时,它将不会暂停。 但是,你可以从调试器中暂停它,然后向其发送一个 Resume 事件,以便调试你的代码。 确保“调试位置”工具栏可见并单击“暂停”图标旁边的下拉列表。 然后选择“恢复”

对于 Windows Phone 应用商店应用,Resuming 事件始终后跟 OnLaunched,即使你的应用当前已暂停且用户从主要磁贴或应用列表中重新启动它也是如此。 如果当前窗口上已有内容集,应用可跳过初始化。 你可以检查 LaunchActivatedEventArgs.TileId 属性以确定该应用是从主要磁贴启动还是从辅助磁贴启动,并可根据该信息,确定是应显示新的应用体验还是应恢复应用体验。