1

In my app both the app and a background task access a file and whichever opens the file first, the other one will fail.

to avoid that happening, I want to stop the background task when the user opens the app, and don't run the background if the app is already open.

How to know from background task if app is running or not? and how to stop it before app starts? thanks.


This is how I register the background task:

var result = await BackgroundExecutionManager.RequestAccessAsync();

var builder = new BackgroundTaskBuilder();
builder.Name = taskName;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
builder.AddCondition(condition);

BackgroundTaskRegistration task = builder.Register();

There is a UserNotPresent condition that specifies the task can run only if user is not present. But I don't understand by present it means user is working with the app, or with phone.

Blendester
  • 1,583
  • 4
  • 19
  • 43
  • [This](https://stackoverflow.com/questions/38555407/check-if-application-is-running-from-a-background-task/38560015#38560015) might help. – Mehrzad Chehraz May 26 '17 at 17:49

1 Answers1

0

The UserNotPresent condition indicates that the user isn't currently using the entire device.

Is your task an in-process background task or an out-of-process background task? I would suggest using in-proc tasks to avoid difficult cross-proc communication scenarios and to simplify the structure of your projects.

Back to your actual question of determining if an app is up from a background task:

For in-process tasks you can check the visibility state of the app to see if it is in the foreground. This can be done in a couple different ways:

  • Set an IsInForeground flag to true in LeavingBackground that is then set to false in EnteredBackground. You can then check the flag to see if the app is up in the foreground.
  • Use the visibility of the Window. Using CoreWindow.GetForCurrentThread().Visible or Window.Current.Visible will enable you to see if the app if is in the foreground, minimized or running headless in the background. Both are true when in foreground and false when minimized. CoreWindow.GetForCurrentThread() will return null and trying to access Window.Current will throw an exception while the app is headless.

For out-of-process tasks you can communicate with the foreground app to determine whether it is present. This can be accomplished using one of the methods suggested here: Check if application is running from a background task

How to stop a background task

Ensure the deferral from the background task instance is released and then just return from your primary method (either Run() for out-of-proc or BackgroundActivated() for in-proc). If there is nothing else running in the process then it will exit.

chcortes
  • 116
  • 4