Created
October 22, 2018 16:57
-
-
Save JerryNixon/21c5785e3c1f8d6e4a7add40936ae805 to your computer and use it in GitHub Desktop.
Preventing UWP Suspension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed partial class App : Application | |
{ | |
public App() | |
{ | |
InitializeComponent(); | |
Suspending += (s, e) => Helpers.ShowToast("Suspending"); | |
Resuming += (s, e) => Helpers.ShowToast("Resuming"); | |
Helpers.SetupExSession( | |
allowed: () => Helpers.ShowToast("Allowed"), | |
denied: () => Helpers.ShowToast("Denied"), | |
revoked: () => Helpers.ShowToast("Revoked")); | |
} | |
protected override void OnLaunched(LaunchActivatedEventArgs e) | |
{ | |
if (!(Window.Current.Content is Frame frame)) | |
{ | |
Window.Current.Content = frame = new Frame(); | |
} | |
if (e.PrelaunchActivated == false) | |
{ | |
if (frame.Content == null) | |
{ | |
frame.Navigate(typeof(MainPage), e.Arguments); | |
} | |
Helpers.ShowToast("Launched"); | |
Window.Current.Activate(); | |
} | |
} | |
} | |
public static class Helpers | |
{ | |
public static void ShowToast(string text) | |
{ | |
var content = new ToastContent | |
{ | |
Visual = new ToastVisual | |
{ | |
BindingGeneric = new ToastBindingGeneric | |
{ | |
Children = | |
{ | |
new AdaptiveText { Text = text } | |
} | |
} | |
} | |
}; | |
var toast = new ToastNotification(content.GetXml()); | |
ToastNotificationManager.CreateToastNotifier().Show(toast); | |
} | |
public static async void SetupExSession(Action allowed, Action denied, Action revoked) | |
{ | |
var session = new ExtendedExecutionSession | |
{ | |
Reason = ExtendedExecutionReason.Unspecified | |
}; | |
session.Revoked += (s, e) => revoked?.Invoke(); | |
var result = await session.RequestExtensionAsync(); | |
switch (result) | |
{ | |
case ExtendedExecutionResult.Allowed: | |
allowed?.Invoke(); | |
break; | |
default: | |
case ExtendedExecutionResult.Denied: | |
denied?.Invoke(); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should be able to replace the app.xaml.cs of any new blank UWP project and test this.