Using the below references, I attempted to make a background task in a UWP app:
https://docs.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task
https://docs.microsoft.com/en-us/windows/uwp/launch-resume/run-a-background-task-on-a-timer-
https://www.youtube.com/watch?v=H18HrUin46I
Everything works as shown in the YouTube video when forcing the background task to run in debug mode, but the debug/release version on the app will not kick off the 15 minute background task on it's own. Here's the code:
MainPage.xaml.cs
using TimerBG;
bool taskRegistered = false;
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == nameof(BG))
{
task.Value.Unregister(true);
}
}
if(!taskRegistered)
{
Setup();
}
public async static void Setup()
{
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = nameof(BG);
builder.TaskEntryPoint = typeof(BG).ToString();
TimeTrigger trig = new TimeTrigger(15, false);
builder.SetTrigger(trig);
SystemCondition userCondition = new SystemCondition(SystemConditionType.UserNotPresent);
builder.AddCondition(userCondition);
builder.CancelOnConditionLoss = false;
builder.Register();
}
BG.cs
using Windows.ApplicationModel.Background;
using Windows.Storage;
namespace TimerBG
{
public sealed class BG : IBackgroundTask
{
BackgroundTaskDeferral _deferral;
public async void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
await FileIO.WriteTextAsync(sampleFile, DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString());
_deferral.Complete();
}
}
}
The package manifest background tasks property is set to "Timer" with the Entry Point as "TimerBG.BG".