Kenny
Kenny

Reputation: 1152

Run background task at startup

I'm trying to run my background task when I log in into my device right after turning it on. Right now it only runs when I was already logged and I log back in.

I can see that the task is registered perfectly while debugging, still don't know why it doesn't work at startup yet.

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);
        }
    }
}

Upvotes: 4

Views: 1525

Answers (2)

Kenny
Kenny

Reputation: 1152

I unregistered the background task and registered it again, it solved the issue that I was having.

Upvotes: 1

Nasser AlNasser
Nasser AlNasser

Reputation: 1775

Please refer to this question.. I believe it's so related to yours:

Uwp execute backgroundtask at user login

Good luck!

Upvotes: 0

Related Questions