如何查看我的基于 JavaScript 的 UWP 在 "background task" 上下文中是否为 运行?

How can I see if my JavaScript-based UWP is running in a "background task" context?

UWP 支持 "background tasks", which run in the background, for example in response to some system event or to implement an App Service.

基于

JavaScript 的 UWP 应用程序在其各自的应用程序清单文件 (.appxmanifest) 中声明 background tasks

检测我的代码是否 运行 作为后台任务的最佳做法是什么?

根据指南,首先您需要创建后台任务 class 并在您的应用不在前台时将其注册到 运行。

后台任务与应用程序解耦,它们运行分开,但后台任务的进度和完成可以通过应用程序代码监控。为了实现这一点,应用程序从它已向系统注册的后台任务订阅事件。 您可以使用 BackgroundTaskProgressEventHandler

var backgroundTaskProgressEventHandler = function(sender, args) {
 /* Your code */
}

UWP "background tasks" are implemented as modified web workers. Detecting web worker context is covered in some other SO questions (1, 2)。一种解决方案如下:

function inBackgroundTaskContext() {
    return typeof importScripts === 'function'
}

importScripts 是一个可以从 web worker 上下文中调用的函数。当应用程序在 "normal" 应用程序上下文中 运行 时未定义。

我假设如果您问这个问题,您已经构建、注册并执行了一个后台任务,该任务只能使用 ApplicationTrigger (https://docs.microsoft.com/en-us/uwp/api/windows.applicationmodel.background.applicationtrigger). If you have not, then your app may be in prelaunch (https://docs.microsoft.com/en-us/windows/uwp/launch-resume/handle-app-prelaunch) 从 UI 线程完成。否则,您应该能够在调用 requestAsync() 之前和之后以编程方式自行处理报告,或者通过 Windows.UI.WebUI.WebUIBackgroundTaskInstance.Progress

在后台任务中报告来跟踪后台任务的进度