Windows10 Dev - Background Execution
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.
Windows10 Dev - Background Execution的更多相关文章
- Executing a Finite-Length Task in the Background
[Executing a Finite-Length Task in the Background] Apps that are transitioning to the background can ...
- iOS之ShareSDK实现分享、第三方登录等功能
(1)官方下载ShareSDK iOS 2.8.8,地址:http://sharesdk.cn/ (2)根据实际情况,引入相关的库,参考官方文档. (3)在项目的AppDelegate中一般情况下有三 ...
- iOS开发---集成ShareSDK实现第三方登录、分享、关注等功能。
(1)官方下载ShareSDK IOS 2.9.6,地址:http://sharesdk.mob.com/Download (2)根据实际情况,引入相关的库,参考官方文档. (3)在项目的AppDel ...
- IOS项目集成ShareSDK实现第三方登录、分享、关注等功能。
(1)官方下载ShareSDK iOS 2.8.8,地址:http://sharesdk.cn/ (2)根据实际情况,引入相关的库,参考官方文档. (3)在项目的AppDelegate中一般情况下有三 ...
- iOS 和 Android 中的后台运行问题
后台机制的不同,算是iOS 和 Android的一大区别了,最近发布的iOS7又对后台处理做了一定的更改,找时间总结一下编码上的区别,先做个记录. 先看看iOS的把,首先需要仔细阅读一下Apple的官 ...
- oc常见误区
1.同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作, 2.异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然 ...
- IOS项目集成ShareSDK实现第三方登录、分享、关注等功能(备用)
(1)官方下载ShareSDK iOS 2.8.8,地址:http://sharesdk.cn/ (2)根据实际情况,引入相关的库,参考官方文档. (3)在项目的AppDelegate中一般情况下有三 ...
- iOS极光推送
昨天花了一下午的时间研究了下极光推送,也前也是没做过,不知道从何下手!才开始的时候一看官方的SDK感觉好难,不过经过一系列的捣鼓之后,手机收到了推送信息,感觉其实并没有那么难! 1.配置开发证书(得有 ...
- iOS极光推送的基本使用
昨天花了一下午的时间研究了下极光推送,也前也是没做过,不知道从何下手!才开始的时候一看官方的SDK感觉好难,不过经过一系列的捣鼓之后,手机收到了推送信息,感觉其实并没有那么难! 1.配置开发证书(得有 ...
随机推荐
- [刘阳Java]_Spring相关配置介绍_第5讲
这一节我们介绍一下Spring框架的相关常用配置 Spring依赖注入的两种方式(构造方法注入和setter方式注入) p-namespace方式配置 properties属性文件配置方式 集合对象配 ...
- ORM研究3 - odoo fields常用的字段属性
之前我们已经讲解了odoo ORM中的一些对字段常用的API操作方法,今天我们继续研究一下Odoo orm中字段的一些通用属性字段的使用,学会它们可以为自己创建数据映射并使用有更好的帮助. 通用字段属 ...
- 一张图概括mysql的各种join用法
- K8S系列第三篇(Docker网络)
目录 docker 网络 Docker 的四种网络模 一.网络基础 1.网络名称空间介绍 2.创建一个命名空间 1)Veth设备对 2)Veth设备操作 1> 创建Veth设备对 2> 绑 ...
- javascript学习(五)之标准对象
一.RegExp:正则表达式是一种用来匹配字符串的强有力的武器.它的设计思想是用一种描述性的语言来给字符串定义一个规则, 凡是符合规则的字符串,我们就认为它"匹配"了,否则,该字符 ...
- Supervisord 远程命令执行漏洞(CVE-2017-11610)
漏洞影响范围: Supervisor version 3.1.2至Supervisor version 3.3.2 poc 地址.https://github.com/vulhub/vulhub/tr ...
- 论文笔记:(NIPS2018)PointCNN: Convolution On X-Transformed Points
目录 摘要 一.2D卷积应用在点云上存在的问题 二.解决的方法 2.1 idea 2.2 X-conv算子 2.3 分层卷积 三.实验 3.1分类和分割 3.2消融实验.可视化和模型复杂度 总结 仍存 ...
- noip模拟30[毛毛毛探探探]
\(noip模拟30\;solutions\) 所以说,这次被初中的大神给爆了????? 其实真的不甘心,这次考场上的遗憾太多,浪费的时间过多,心情非常不好 用这篇题解来结束这场让人伤心的考试吧 \( ...
- 大厂需要什么样的 Android 开发?
前言 昨天和一个百度的朋友闲聊,他说根据最近招聘 Android工程师的经验来看,大部分候选人在工作 3 年的时候基本都会遇上一道难过的坎. 为啥这么说呢? 因为工作一段时间之后,大部分工程师都已经完 ...
- 阿里三面Android开发岗都过了,但是无理由挂了,竟是HR骚操作?
进入互联网大厂一般都是"过五关斩六将",难度堪比西天取经,但当你真正面对这些大厂的面试时,有时候又会被其中的神操作弄的很是蒙圈. 近日,某位程序员发帖称,自己去阿里面试Androi ...