Search code examples
win-universal-appbackground-task

Background Task does not run in UWP


I have a UWP application where I want to add background task support for doing certain things while my application is in background. I am doing exactly as it is mentioned here: https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task

I have one separate project for Background Tasks and in my package manifest file I have declared that my app uses background tasks (but "timer" task since I am using TimerTrigger). Code:

BackgroundTaskBuilder backgroundTaskBuilder = new BackgroundTaskBuilder { Name = "NotificationUpdater", TaskEntryPoint = "NamespaceOfMyBackgroundTaskInterfaceImplementation.BackgroundTask"};

backgroundTaskBuilder.SetTrigger(new TimeTrigger(15, false));

BackgroundTaskRegistration backgroundTaskRegistration = backgroundTaskBuilder.Register();

Now, when I launch my app (via Visual Studio), and use Lifecycle Events dropdown to suspend my app, it never executes the Run() method in the BackgroundTask class (implementation of IBackgroundTask interface). Code inside BackgroundTask class:

namespace NamespaceOfMyBackgroundTaskInterfaceImplementation
{
    public sealed class BackgroundTask : IBackgroundTask
    {
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //Code to run in the background
        }
    }
}

Solution

  • As it turned out in the conversation, the problem was in wrong declaration of project type. In should be a Windows Runtime Component.

    For the followers, please take a look at this answer, which describes the steps. It answers to Silverlight 8.1, but the process and steps are the same in WinRT and UWP.