1
votes

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

JavaScript-based UWP apps declare background tasks in their respective application manifest files (.appxmanifest).

What is the best practice to detect whether my code is running as a background task?

3

3 Answers

0
votes

I assume if you are asking this question, you have built, registered, and executed a background task, which can only be done from the UI thread using the 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). Otherwise, you should be able to handle reporting that yourself programmatically before and after you call requestAsync() or track progress of your background task through reporting within your background task via Windows.UI.WebUI.WebUIBackgroundTaskInstance.Progress

-1
votes

As per guidance, first you need to Create a background task class and register it to run when your app is not in the foreground.

Background tasks are decoupled from the app, and they run separately, but background task progress and completion can be monitored by app code. To make this happen, the app subscribes to events from the background task(s) it has registered with the system. You can use the BackgroundTaskProgressEventHandler

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

UWP "background tasks" are implemented as modified web workers. Detecting web worker context is covered in some other SO questions (1, 2). One solution is the following:

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

importScripts is a function that is callable from within a web worker context. It is not defined when the app is running within a "normal" app context.