Reputation: 537
Using the below references, I attempted to make a background task in a UWP app:
https://learn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task
https://learn.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".
Upvotes: 0
Views: 955
Reputation: 537
Found the solution after reading the article:
https://learn.microsoft.com/en-us/windows/uwp/launch-resume/debug-a-background-task
Background tasks and Visual Studio package deployment
If an app that uses background tasks is deployed using Visual Studio, and the version (major and/or minor) specified in Manifest Designer is then updated, subsequently re-deploying the app with Visual Studio may cause the app’s background tasks to stall. This can be remedied as follows:
Upvotes: 1