advertisement
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
}
}
116
Windows 10 Apps Development
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();
117
Windows 10 Apps Development
Let us understand a simple example of background task by following all the below given steps.
1. 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>
2. 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 http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 documented at 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
{
118
Windows 10 Apps Development
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();
119
Windows 10 Apps Development
await trigger.RequestAsync();
}
}
}
}
3. 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.
4. 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)
{
120
Windows 10 Apps Development
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);
}
}
}
5. To make this project accessible in the UWPBackgroundDemo project, right click on
References > Add References in Solution Explorer and add BackgroundStuff project.
6. Now, let us go to the Package.appxmanifest file of
UWPBackgroundDemo
project and add the following information in Declarations tab.
121
Windows 10 Apps Development
7. First build the Background stuff project, then build and execute the
UWPBackgroundDemo project.
8. When the above code is compiled and executed, you will see the following window.
9. When you click the button, it will run the background task and will show a notification at the right end of your window.
122
advertisement
Related manuals
advertisement
Table of contents
- 5 Introduction
- 5 Universal Windows app
- 6 Characteristics of UWP apps
- 6 Development Choices
- 7 Windows 10 – UWP
- 7 Universal Windows Platform (UWP)
- 8 Devices Supported by Windows
- 8 Advantages of UWP
- 8 Setup for UWP Development
- 10 Windows 10 – First App
- 19 Windows 10 – Store
- 20 Monetization
- 20 Microsoft Advertising
- 27 Windows 10 – XAML Controls
- 27 XAML Emerging Story
- 28 Layout Controls
- 29 UI Controls
- 35 XAML – Data Binding
- 35 One-way Data Binding
- 37 Two-way Data Binding
- 40 Element Binding
- 43 XAML Performance
- 43 Progressive Rendering
- 47 Deferred Loading
- 51 Adaptive Design
- 51 New Built-in Features
- 52 Universal Building Blocks
- 54 Adaptive UI
- 54 VisualStateManager
- 56 RelativePanel
- 59 Adaptive Code
- 59 Writing Code
- 61 Win32 APIs in the UWP
- 70 File Management
- 70 File Locations
- 71 File Handling APIs
- 77 SQLite Database
- 77 What is SQLite?
- 77 Advantages of SQLite
- 89 App to App Communication
- 89 Getting Your App Ready
- 96 App Localization
- 96 Translating UI Resources
- 112 App Lifecycle
- 113 Process State Transition
- 120 Background Execution
- 120 Create and Register Background Task
- 127 APP Services
- 136 Web Platform
- 136 Advantages
- 143 Connected Experience
- 144 Roaming in Windows
- 151 Navigation
- 151 Page Models
- 151 Navigation Structure
- 158 Networking
- 158 Capabilities
- 159 Networking Technologies
- 162 HttpClient
- 164 Cloud Services
- 164 Microsoft Account
- 175 Live Tiles
- 175 Tile Anatomy
- 175 Updating Tiles
- 180 Sharing Contract
- 180 Sharing Content
- 181 Receiving Shared Content
- 188 Porting to Windows
- 188 Porting a Windows 8.x Project to a UWP Project