The Universal Windows Platform (UWP) introduces new mechanisms, which allow the applications to perform some functionality while the application is not running in the foreground. UWP also increases the ability of the applications to extend their execution time in the background for Background Tasks and Triggers. Background execution is the real complementary tail to the application lifecycle.
Important features of Background Tasks are −
-
A background task is triggered by a system or time event and can be constrained by one or more conditions.
-
When a background task is triggered, its associated handler runs and performs the work of the background task.
-
A background task can run even when the app that registered the background task is suspended.
-
They are part of the standard application platform and essentially provide an app with the ability to register for a system event (trigger). When that event occurs, they run a predefined block of code in the background. System triggers include events such as changes in network connectivity or the system time zone.
-
Background Execution is not guaranteed, so it is not suitable for critical functions and features.
-
The OS has a limitation as to how many background tasks can run at the same time. So even when trigger is fired and conditions are met, the task can still not run.
Create and Register Background Task
Create a background task class and register it to run when your app is not in the foreground. You can run code in the background by writing classes that implement the IBackgroundTask interface. The following sample code shows a very basic starting point for a background task class.
public sealed class MyBackgroundTask : IBackgroundTask {
public void Run(IBackgroundTaskInstance taskInstance){
// write code
}
}
You can request access for background task as follows.
var access = await BackgroundExecutionManager.RequestAccessAsync();
switch (access) {
case BackgroundAccessStatus.Unspecified:
break;
case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
break;
case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
break;
case BackgroundAccessStatus.Denied:
break;
default:
break;
}
To build and register the background task, use the following code.
var task = new BackgroundTaskBuilder {
Name = "My Task",
TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString()
};
var trigger = new ApplicationTrigger();
task.SetTrigger(trigger);
task.Register();
await trigger.RequestAsync();
Let us understand a simple example of background task by following all the below given steps.
-
Create a new blank UWP project ‘UWPBackgroundDemo’ and add one button in the XAML file.
<Page
x:Class = "UWPBackgroundDemo.MainPage"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local = "using:UWPBackgroundDemo"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable = "d">
<Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name = "button" Content = "Button"
HorizontalAlignment = "Left" Margin = "159,288,0,0"
VerticalAlignment = "Top" Click = "button_Click"/>
</Grid>
</Page>
-
Given below is the button click event implementation in which the background task is registered.
using System;
using Windows.ApplicationModel.Background;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at
http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWPBackgroundDemo {
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
}
private async void button_Click(object sender, RoutedEventArgs e) {
var access = await BackgroundExecutionManager.RequestAccessAsync();
switch (access){
case BackgroundAccessStatus.Unspecified:
break;
case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
break;
case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
break;
case BackgroundAccessStatus.Denied:
break;
default:
break;
}
var task = new BackgroundTaskBuilder {
Name = "My Task",
TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString()
};
var trigger = new ApplicationTrigger();
task.SetTrigger(trigger);
var condition = new SystemCondition(SystemConditionType.InternetAvailable);
task.Register();
await trigger.RequestAsync();
}
}
}
-
Now create another project, but this time select Windows Runtime Component (Universal Windows) from the menu and give the name Background stuff to this project.
-
Given below is the C# code. which contains MyBackgroundTask class implantation and it will run the background task.
using Windows.ApplicationModel.Background;
using Windows.UI.Notifications;
namespace BackgroundStuff {
public sealed class MyBackgroundTask : IBackgroundTask {
public void Run(IBackgroundTaskInstance taskInstance) {
SendToast("Hi this is background Task");
}
public static void SendToast(string message) {
var template = ToastTemplateType.ToastText01;
var xml = ToastNotificationManager.GetTemplateContent(template);
var elements = xml.GetElementsByTagName("Test");
var text = xml.CreateTextNode(message);
elements[0].AppendChild(text);
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}
-
To make this project accessible in the UWPBackgroundDemo project, right click on References > Add References in Solution Explorer and add BackgroundStuff project.
-
Now, let us go to the Package.appxmanifest file of UWPBackgroundDemo project and add the following information in Declarations tab.
-
First build the Background stuff project, then build and execute the UWPBackgroundDemo project.
-
When the above code is compiled and executed, you will see the following window.
-
When you click the button, it will run the background task and will show a notification at the right end of your window.