KeepScreenOnRequest.RequestActive 不工作

KeepScreenOnRequest.RequestActive Not Working

对于我的 Windows 商店应用程序,我希望我的应用程序始终处于活动状态。

我正在使用下面的代码。我的设备设置为在 10 秒内进入屏幕锁定,而当我使用我的应用程序时它仍然进入锁定屏幕。我是否错误地使用了此代码?

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    // Prevent tablet from sleeping while app is running
    Windows.System.Display.DisplayRequest KeepScreenOnRequest = new Windows.System.Display.DisplayRequest();
    KeepScreenOnRequest.RequestActive();
}

我认为您应该在页面导航事件而不是应用程序级事件上尝试...

using Windows.System.Display;

private DisplayRequest KeepScreenOnRequest;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    if(KeepScreenOnRequest == null)
        KeepScreenOnRequest = new DisplayRequest();

    KeepScreenOnRequest.RequestActive();
}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    base.OnNavigatingFrom(e);

    KeepScreenOnRequest.RequestRelease();
}

再次在这种情况下,您必须单独处理所有应用程序页面上的请求和发布部分...

我认为问题可能出在其他地方 - 您的 DisplayRequest 可能已被垃圾回收。像这样尝试:

Windows.System.Display.DisplayRequest KeepScreenOnRequest;

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    KeepScreenOnRequest = new Windows.System.Display.DisplayRequest();
    // Prevent tablet from sleeping while app is running
    KeepScreenOnRequest.RequestActive();
}

几点注意事项:

  • 当然上面的代码应该适用于整个应用程序,当不需要时 - 释放请求
  • 将它放在 OnNavigatedFrom/OnNavigatedTo 中可能不是一个好主意,除非处理得当 - 例如当应用程序在您 [=36= 之后暂停时(常见情况) ] OnNavigated 不会被调用 - 您的 DisplayRequest 可能不会被激活
  • 您无需担心在应用程序进入后台时释放您的请求,as mentioned at MSDN:

    Note Windows automatically deactivates your app's active display requests when it is moved off screen, and re-activates them when your app comes back to the foreground.