This blog post is part of a series about how Windows Phone 8.1 affects developers. This blog post talks how to mulitask with background agents and is written by Robert Hedgate at Jayway and was originally posted here.
We now have triggers. This is what will trigger the background task to start. There are a lot of trigger e g TimeZoneChange, UserAway, SmsReceived and more. Some of these require the app to be put on the lock screen. Below I show an example of how to use a trigger: Create a Windows Runtime Component. Add a class which inherits from IBackgroundTask. This will create a Run method in your class. This is the method which will be run when the trigger is activated.
public sealed class Bg : IBackgroundTask
public void Run(IBackgroundTaskInstance taskInstance)
Add this class to the appxmanifest declarations:
Then in your code create a builder and add a trigger and register it.
const string name = "MyExampleTrigger";
if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == name))
// One register it once
var builder = new BackgroundTaskBuilder();
var trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);
builder.Name = name;
builder.TaskEntryPoint = typeof(BackgroundTasks.Bg).FullName;
var registration = builder.Register();
registration.Completed += RegistrationOnCompleted;
RegistrationOnCompleted will be called when the background task is completed. There are also a Progress event to listen to if you want. There are limitation on how much memory, CPU time etc you are allowed to use. To maximize the amount call:
var result = await BackgroundExecutionManager.RequestAccessAsync();
if (result == BackgroundAccessStatus.Denied)
// Handle this if it is importet for your app.
If the result is denied the phone thinks it has too much background task active. In that case you can prompt your users to go the Battery saver application and force allow your app to run in the background even if the phone don´t want to. Just ask nice and I’m sure the user will do this for your super app J.
var downloader = new BackgroundDownloader();
var download = downloader.CreateDownload(source, destinationFile);
await download.StartAsync().AsTask(cts.Token, progressCallback);