Background tasks come in handy when you want your app to do something even if it isn’t currently running on your device. Once of the most common things to do is update your live tile.
Background tasks run in a separate process from your app and are installed at the same time you app is installed. Because it’s a separate process it needs to be a separate assembly. So the first thing we need to do is add a new project to your current apps solution. Let’s get started:
Create the background task project
- In Solution Explorer, right click on your solution (Not the project) and select Add->New Project.
If you can only see your UWP project and not the solution have a look at this article: Only Project Displayed In Visual Studio
- In the Add New Project window, select Visual Basic->Windows->Universal and then select the Windows Runtime Component template
- Give your background task a project name, set the project location and click on OK to add the project to your solution
- Click on your app project in Solution Explorer (not the background task you just added) and click on the Project menu followed by Add Reference
- In the Reference Manager window, select Projects->Solution. You should see your background task listed. Select it by ticking its checkbox and click on OK
Setting up the background task
Next we need to write our code that the background task will call. What we don’t want is our task ending before our code has finished, so we are going to run our task as a deferral.
- Delete the class.vb file that was automatically added when you created the background task project.
- Add a new class file called UpdateLiveTile.vb
- Add the following imports to the new class File
Imports Windows.ApplicationModel.Background Imports Windows.Data.Xml.Dom Imports Windows.UI.Notifications
Public Class UpdateLiveTile
Public NotInheritable Class UpdateLiveTile Implements IBackgroundTask
- Important! Do Not use a NAMESPACE around your class definition.
- We now need to implement a IBackgroundTask_Run subroutine that is called when the background task is called. Add the following code:
Private Sub IBackgroundTask_Run(taskInstance As IBackgroundTaskInstance) Implements IBackgroundTask.Run Dim deferral As BackgroundTaskDeferral = taskInstance.GetDeferral() SetLiveTile() deferral.Complete() End Sub
- Add in our code that updates the Live Tile:
Private Sub SetLiveTile() Dim tileString As String = "<tile>" & "<visual>" & "<binding template=""TileSmall"">" & "<text>TIME</text>" & "</binding>" & "<binding template=""TileMedium"">" & "<text>TIME</text>" & "</binding>" & "<binding template=""TileWide"">" & "<text>TIME</text>" & "</binding>" & "<binding template=""TileLarge"">" & "<text>TIME</text>" & "</binding>" & "</visual>" & "</tile>" tileString = tileString.Replace("TIME", DateTime.Now.ToString) Dim tileXML As New XmlDocument tileXML.LoadXml(tileString) Dim updater = TileUpdateManager.CreateTileUpdaterForApplication() updater.EnableNotificationQueue(True) updater.Clear() updater.Update(New TileNotification(tileXML)) End Sub
The above is a very simple Live Tile that shows the current date and time. For documentation on creating the XML for your Live Tiles and what features are possible see this page: Create adaptive tiles
Set up your package manifest
The next thing you have to do is set up your package manifest and register the background task with your app.
- In the Solution Explorer under your apps project, open Package.appxmanifest
- Click on the Declarations tab
- Using the Available Declarations drop down select Background Tasks and click on Add
- Under Supported task types tick the Time checkbox
- under App settings set the entry point to BackgroundTasks.UpdateLiveTile
(This is the namespace and class name from our background task project)
- Click on the Application tab
- Set Lock screen notifications dropdown to Badge and Tile text
- Click on the Visual Assets tab and select Badge Logo
- Ensure you have a Badge Logo (24×24) and Small Logo (30×30) assigned
- Click on Wide Logo and ensure you have a 310×150 assigned also
Register the background task within your app
When your app starts it needs to register your background task on the device. The minimum time interval of a background task is 15 minutes. Even if you set the interval to 15 it could take up to 30 minutes before your background task is executed.
It’s up to you where you want to register your background task. I prefer to do this when the app starts so lets edit the App.xaml.vb code:
- Add the following import
- Add the following subroutine:
Private Const taskName As String = "UpdateLiveTileBackgroundTask" Private Const taskEntryPoint As String = "BackgroundTasks.UpdateLiveTile" Private Async Sub RegisterBackgroundTask() Dim btAccessStatus = Await BackgroundExecutionManager.RequestAccessAsync() If btAccessStatus = BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity OrElse btAccessStatus = BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity Then For Each task In BackgroundTaskRegistration.AllTasks If task.Value.Name = taskName Then task.Value.Unregister(True) End If Next Dim taskBuilder As New BackgroundTaskBuilder() taskBuilder.Name = taskName taskBuilder.TaskEntryPoint = taskEntryPoint taskBuilder.SetTrigger(New TimeTrigger(30, False)) Dim registration = taskBuilder.Register() End If End Sub
This removes the background task if it is already registered and the registers it again as a new process.
Note on line 15 where we have set the time interval to 30 minutes. More information on TimeTrigger can be found here: Run a background task on a timer
- Now just call the register sub from the OnLaunched sub:
Protected Overrides Async Sub OnLaunched(e As Windows.ApplicationModel.Activation.LaunchActivatedEventArgs) ... Call RegisterBackgroundTask() ... End Sub
- Run your solution to register the background task. Check your live has updated after the TimeTrigger interval has expired (in this example it could take up to 45 minutes)
How to make sure your Background Task is working
Adding a breakpoint to your background task won’t work on its own. To make sure the background task is registered correctly and your code is working as you expect do the following:
- Edit the UpdateLiveTile.vb code, highlight the line where we define the deferral and press F9 to add a Breakpoint
- In Visual Studio, click on the View menu followed by Toolbars. Make sure Debug Location is checked
- Run your app and once your background register code has been executed, switch back to Visual Studio while the app is still running
- Using the Debug Location toolbar you should see a drop down after the name of your apps process name. This usually says Lifecycle Events. Click on the drop down and you will see the task process UpdateLiveTileBackgroundTask, select it.
- This forces the background task to execute and your breakpoint will now be hit. From here you can debug and test as required
Pass data between your app and background task
As we found out before, your background task runs in a separate process from your app. You can’t actually pass data between the two. However your background task uses the same data storage as your app. This means you can store a value from your app in LocalSettings for example and then retrieve it from your background task:
Dim localSettings As Windows.Storage.ApplicationDataContainer = Windows.Storage.ApplicationData.Current.LocalSettings Dim MyValue As String = localSettings.Values("MyValue")