I am trying to start a background task when I log in to my device immediately after it is turned on. Now it starts only after I have already been registered and I logged in again.
I see that the task is being logged perfectly during debugging, I still don’t know why it still doesn’t work at startup.
async void RequestBackgroundAccess()
{
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified)
{
RegisterBackgroundThread();
}
else
{
Debug.WriteLine("[Background Access] Denied.");
}
}
void RegisterBackgroundThread()
{
var taskRegistered = false;
var exampleTaskName = "Bot";
foreach (var bgTask in BackgroundTaskRegistration.AllTasks)
{
if (bgTask.Value.Name == exampleTaskName)
{
taskRegistered = true;
Debug.WriteLine("[Background Task] Registered.");
break;
}
}
if (taskRegistered == false)
{
Debug.WriteLine("[Background Task] Registering...");
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Tasks.Bot";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.UserPresent, false));
BackgroundTaskRegistration task = builder.Register();
Debug.WriteLine("[Background Task] Registered.");
}
}
Bot.cs
namespace Tasks
{
public sealed class Bot : IBackgroundTask
{
BackgroundTaskDeferral serviceDeferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
this.serviceDeferral = taskInstance.GetDeferral();
ToastNotification("Starting...");
}
void ToastNotification(String message)
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode(message));
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}
Kenny source
share