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.

Windows phone 8

In windows phone 8 we have something called Background agents and schedule tasks. Working with these API is a bit difficult since there are constraints suck as expiration time etc.

 

Windows phone 8.1

With windows phone 8.1 we now have the same way of working with multitasking as in Windows 8.1. If however you have invested much time in the old way but still want to use the new 8.1 API:s upgrade to Silverlight 8.1 and continue to use the background agents. You can use the new multitasking in Silverlight 8.1 as well but do not use both version at the same time, it will function poorly due to the operating system will use the same API at the same time.

 

What’s new then

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: clip_image002

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

var builder = new BackgroundTaskBuilder();
var trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);

builder.Name = name;
builder.TaskEntryPoint = typeof(BackgroundTasks.Bg).FullName;
builder.SetTrigger(trigger);

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.

What’s completely new

In windows phone 8.1 there are some new triggers that just make sense on the phone to have:
  • GattCharacteristicNotificationTrigger (bluetooth)
  • DeviceChangeTrigger
  • DeviceUpdateTrigger
  • RfcommConnectionTrigger.
There are however some trigger removed as well compared to window 8.1:
  • OnlineIdConnectedStateChange
  • LockScreenApplicationAdded
  • LockScreenApplicationRemoved
  • ControlChannelTrigger
And then again there are some things which are available in Silverlight 8.1 but not in Windows phone 8.1:
  • Continuous Background Location
  • Runs Under Lock
  • VoIP Agents
  • Wallet Agents

 

Background transfer

The old way with using the Microsoft.Phone.BackgroundTransfer namespace there was a lot of limitaions, size, requests etc. Now the phone is using Windows.Networking.BackgroundTransfer the same as windows 8.1 with no size limitation, in progress stream access etc. It does however use the Battery saver and will halt or stop your download/upload if you are near datalimit etc. It is quite easy to set up a download:
var downloader = new BackgroundDownloader();
var download = downloader.CreateDownload(source, destinationFile);

await download.StartAsync();
It is also possible to add progress and cancel tokens to the download object if it is a long operation.
await download.StartAsync().AsTask(cts.Token, progressCallback);
I recommend you to look at this very good example http://code.msdn.microsoft.com/windowsapps/Background-Transfer-Sample-d7833f61/ which shows how background worker functions. It is also made as an Universal app which is nice to see how easy it can be. As always there are also a MSDN link http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.aspx.

 

Summary:

Windows Phone 8.1 now have the same background functions as in Windows 8.1. This is great and makes it super easy to share the code in a Universal app.