Universal App Tutorials Part 17 : Background Tasks

Live Tile Update Debug Location

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.

Prerequisites

Implementation

Background Task

We’ll need to create a project to house our background tasks, it’ll need to be of type Windows Runtime Component.  Go ahead and create one called MorseCoder.BackgroundAgents.

Windows Runtime Component
Windows Runtime Component

This will create an empty sealed (can’t be inherited) class, rename it LiveTileUpdate, as this is what it will eventually do.

Background Tasks need to inherit from the IBackgroundTask interface.  Implement this interface as follows:

[csharp]
using System;
using Windows.ApplicationModel.Background;

namespace MorseCoder.BackgroundTasks
{
public sealed class LiveTileUpdate : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
throw new NotImplementedException();
}
}
}
[/csharp]

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
Morse Coder Properties

Open the Declarations Tab :

Morse Coder Manifest Declarations
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
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.

Override the OnNavigatedTo event in the MainPage code behind:

[csharp]
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}
[/csharp]

Create a RegisterBackgroundTask method and call it from the OnNavigatedToEvent:

[csharp]
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.RegisterBackgroundTask();
base.OnNavigatedTo(e);
}

private async void RegisterBackgroundTask()
{
var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
}
[/csharp]

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:

[csharp]
private void UnregisterTask(string taskName)
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == taskName)
{
task.Value.Unregister(true);
}
}
}
[/csharp]

Now let’s create a method to help Register our Task:

[csharp]
private void RegisterTask(string taskName, string taskEntryPoint, uint intervalMinutes)
{
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();

taskBuilder.Name = taskName;
taskBuilder.TaskEntryPoint = taskEntryPoint;

taskBuilder.SetTrigger(new TimeTrigger(intervalMinutes, false));

var registration = taskBuilder.Register();
}
[/csharp]

Now we can use our backgroundAccessStatus token to verify that we can remove and register our background task:

[csharp]
private async void RegisterBackgroundTask()
{
var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

if (backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity ||
backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity)
{
UnregisterTask(TaskName);
RegisterTask(TaskName, TaskEntryPoint, TaskIntervalMinutes);
}
}

private const string TaskName = "LiveTileUpdate";
private const string TaskEntryPoint = "MorseCoder.BackgroundTasks.LiveTileUpdate";
private const uint TaskIntervalMinutes = 15;
[/csharp]

In order to Debug the Background Task from the DebugLocation toolbar, once it has been successfully registered it will appear in the dropdown:

Live Tile Update Debug Location
Live Tile Update Debug Location

It won’t appear here until it has been registered with the Application.

Summary

Where are we?

  • We created a BackgroundTasks project;
  • Set up our Application Manifest;
  • Registered it with the Application.

Where are we heading?

  • Implementing a LiveTileUpdate;
  • making the app User Experience (UX) more usable;
  • adding some more functionality to our About Page;
  • methods of serialising POCOs to Application Settings.

 

2 thoughts on “Universal App Tutorials Part 17 : Background Tasks”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s