Universal App Tutorials Part 17 : Background Tasks

UWP apps, like the Windows Phone 7 and 8 platforms before them can have Background Tasks, while a background task for the Morse Coder app might not be enormously useful at this stage, let’s take a look at how to create one. In a further post we will look at updating the Live Tile from our Background Task.

Outcome

By the end of this post we’ll have a Background Task running on a schedule. It won’t do anything, but we will have set up the permission in the manifest, created the project, and our task class and registered it with the application. We will then be ready to implement the task.

Application Manifest

Reference the new MorseCoder.BackgroundTasks project from the base MorseCoder project.

From the Morse Coder Properties, open the Package Manifest :

Morse Coder Properties

Open the Declarations Tab :

Morse Coder Manifest Declarations

Create a new Declaration from the Available Declarations drop down for Background Tasks. The Supported Task Type is Timer, and the entry point is the class we created above, MorseCoder.BackgroundTasks.LiveTileUpdate:

Morse Coder Manifest Declarations Complete

Registering Task at Runtime

Our task now has permission to be registered, let’s look at registering it at run time.

We’ll be overriding the OnNavigatedTo event on our MainPage code behind as our point at which we will register the task. When this gets called, our app will have been initialised and in a sensible state to handle our background task registration, using MVVM, you wouldn’t generally use the code behind but for simplicity sake let’s use it, we may refactor later. Let’s start building it up.

The backgroundAccessStatus variable contains an enumeration of type BackgroundAccessStatus. With this we can verify that we have the correct permissions, or request it via a message box depending on the platform as detailed on the MSDN page.

We need to remove any existing task registrations prior to registering our new task with the same name, you can think of it as a dictionary of key value pairs, let’s create a method to Unregister our task, ideally this would be in a Common library: