UWP基础教程 - 重启应用

时间:2022-05-04
本文章向大家介绍UWP基础教程 - 重启应用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

开发过Winform应用的同学应该都知道,会有一些场景需要将应用重启,如:重新应用配置,崩溃,内存泄漏等情况。这个时候我们只要使用一行代码就可以实现重启。

Application.Restart()

但在之前的Windows10 UWP应用开发中,我们只能提示用户手动重启,这个问题一直很困恼开发者。

在16226版本之后,微软终于实现了这个API。

AppRestartFailureReason result = await CoreApplication.RequestRestartAsync(String.Empty);
if (result == AppRestartFailureReason.NotInForeground || 
    result == AppRestartFailureReason.RestartPending ||
    result == AppRestartFailureReason.Other)
{
    Debug.WriteLine("RequestRestartAsync failed: {0}", result);
}

使用上面的代码就能实现UWP APP重启的功能,这个API还可以自定义启动参数,只要将上述代码String.Empty部分传入对应的参数,在OnActivated事件处进行处理即可。

protected override void OnActivated(IActivatedEventArgs args)
{
    switch (args.Kind)
    {
        case ActivationKind.Launch:
            LaunchActivatedEventArgs launchArgs = args as LaunchActivatedEventArgs;
            string argString = launchArgs.Arguments;
 
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                rootFrame = new Frame();
                Window.Current.Content = rootFrame;
            }
            rootFrame.Navigate(typeof(MainPage), argString);
            Window.Current.Activate();
            break;
    }
}

更详细的内容,大家可以参考微软官方博客写的How to Restart your App Programmatically