- Windows 10 - Porting to Windows
- Windows 10 - Sharing Contract
- Windows 10 - Live Tiles
- Windows 10 - Cloud Services
- Windows 10 - Networking
- Windows 10 - Navigation
- Windows 10 - Connected Experience
- Windows 10 - Web Platform
- Windows 10 - APP Services
- Windows 10 - Background Execution
- Windows 10 - App Lifecycle
- Windows 10 - App Localization
- Windows 10 – Communication
- Windows 10 - SQLite Database
- Windows 10 - File Management
- Windows 10 - Adaptive Code
- Windows 10 - Adaptive UI
- Windows 10 - Adaptive Design
- Windows 10 - XAML Performance
- Windows 10 - Data Binding
- Windows 10 - XAML Controls
- Windows 10 - Store
- Windows 10 – First App
- Windows 10 – UWP
- Windows 10 - Introduction
- Windows 10 - Home
Windows 10 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Windows10 Dev - Background Execution
The Universal Windows Platform (UWP) introduces new mechanisms, which allow the apppcations to perform some functionapty while the apppcation is not running in the foreground. UWP also increases the abipty of the apppcations to extend their execution time in the background for Background Tasks and Triggers. Background execution is the real complementary tail to the apppcation pfecycle.
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 apppcation platform and essentially provide an app with the abipty 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 pmitation 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.
pubpc sealed class MyBackgroundTask : IBackgroundTask { pubpc 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 ApppcationTrigger(); 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-compatibipty/2006" mc:Ignorable = "d"> <Grid Background = "{ThemeResource ApppcationPageBackgroundThemeBrush}"> <Button x:Name = "button" Content = "Button" HorizontalApgnment = "Left" Margin = "159,288,0,0" VerticalApgnment = "Top" Cpck = "button_Cpck"/> </Grid> </Page>
Given below is the button cpck event implementation in which the background task is registered.
using System; using Windows.ApppcationModel.Background; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwpnk/?LinkId=402352&clcid=0x409 namespace UWPBackgroundDemo { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> pubpc sealed partial class MainPage : Page { pubpc MainPage() { this.InitiapzeComponent(); } private async void button_Cpck(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 ApppcationTrigger(); 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.ApppcationModel.Background; using Windows.UI.Notifications; namespace BackgroundStuff { pubpc sealed class MyBackgroundTask : IBackgroundTask { pubpc void Run(IBackgroundTaskInstance taskInstance) { SendToast("Hi this is background Task"); } pubpc 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 cpck 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 cpck the button, it will run the background task and will show a notification at the right end of your window.