[源码下载]

背水一战 Windows 10 (116) - 后台任务: 前台程序激活后台任务

作者:webabcd

介绍
背水一战 Windows 10 之 后台任务

  • 前台程序激活后台任务

示例
演示后台任务的应用(前台程序激活后台任务)
/BackgroundTaskLib/BackgroundTaskFore.cs

/*
* 后台任务,用于演示如何在前台程序通过 api 激活后台任务
*/ using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage; namespace BackgroundTaskLib
{
// 实现 IBackgroundTask 接口,其只有一个方法,即 Run()
public sealed class BackgroundTaskFore : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
// 后台任务在执行中被终止执行时所触发的事件
taskInstance.Canceled += taskInstance_Canceled; // 异步操作
BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try
{
// 指定后台任务的进度
taskInstance.Progress = ;
// taskInstance.InstanceId - 后台任务实例的唯一标识,由系统生成,与前台的 IBackgroundTaskRegistration.TaskId 一致 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdBackgroundTask\fore.txt", CreationCollisionOption.ReplaceExisting);
for (uint progress = ; progress <= ; progress += )
{
await Task.Delay(); // 更新后台任务的进度(会通知给前台)
taskInstance.Progress = progress; // 写入相关数据到指定的文件
await FileIO.AppendTextAsync(file, "progress: " + progress.ToString() + ", currentTime: " + DateTime.Now.ToString() + Environment.NewLine);
}
}
finally
{
// 完成异步操作
deferral.Complete();
}
} void taskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
/*
* BackgroundTaskCancellationReason - 后台任务在执行中被终止执行的原因
* Abort - 前台 app 调用了 IBackgroundTaskRegistration.Unregister(true)
* Terminating - 因为系统策略,而被终止
* LoggingOff - 因为用户注销系统而被取消
* ServicingUpdate - 因为 app 更新而被取消
* ... - 还有好多,参见文档吧
*/
}
}
}

BackgroundTask/Fore.xaml

<Page
x:Class="Windows10.BackgroundTask.Fore"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.BackgroundTask"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="10 0 10 10"> <TextBlock Name="lblMsg" Margin="5" /> <Button Name="btnRegister" Content="注册一个后台任务" Margin="5" Click="btnRegister_Click" />
<Button Name="btnUnregister" Content="注销指定的后台任务" Margin="5" Click="btnUnregister_Click" /> <Button Name="btnRequest" Content="激活后台任务" Margin="5" Click="btnRequest_Click" /> </StackPanel>
</Grid>
</Page>

BackgroundTask/Fore.xaml.cs

/*
* 演示后台任务的应用(前台程序激活后台任务)
*
* 注:
* 1、需要引用后台任务项目,相关代码参见 BackgroundTaskLib/BackgroundTaskFore.cs
* 2、需要在 Package.appxmanifest 添加“后台任务”声明,支持的任务类型选择“常规”,并指定 EntryPoint(后台任务的类全名),类似如下:
* <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTaskLib.BackgroundTaskFore">
* <BackgroundTasks>
* <Task Type="general" />
* </BackgroundTasks>
* </Extension>
*/ using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation; namespace Windows10.BackgroundTask
{
public sealed partial class Fore : Page
{
// 所注册的后台任务的名称
private string _taskName = "Fore"; // 所注册的后台任务的 EntryPoint,即后台任务的类全名
private string _taskEntryPoint = "BackgroundTaskLib.BackgroundTaskFore"; // 后台任务是否已在系统中注册
private bool _taskRegistered = false; // 后台任务执行状况的进度说明
private string _taskProgress = ""; // 实例化一个 ApplicationTrigger 类型的后台任务触发器(由前台程序通过 api 激活后台任务)
private ApplicationTrigger applicationTrigger = new ApplicationTrigger(); public Fore()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 遍历所有已注册的后台任务(避免重复注册)
foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == _taskName)
{
// 如果找到了指定的后台任务,则为其增加 Progress 和 Completed 事件监听,以便前台 app 接收后台任务的进度汇报和完成汇报
AttachProgressAndCompletedHandlers(task.Value);
_taskRegistered = true;
break;
}
} UpdateUI();
} private async void btnRegister_Click(object sender, RoutedEventArgs e)
{
// 在注册后台任务之前,需要调用 BackgroundExecutionManager.RequestAccessAsync(),如果是更新过的 app 则在之前还需要调用 BackgroundExecutionManager.RemoveAccess()
string appVersion = $"{Package.Current.Id.Version.Major}.{Package.Current.Id.Version.Minor}.{Package.Current.Id.Version.Build}.{Package.Current.Id.Version.Revision}";
if ((string)ApplicationData.Current.LocalSettings.Values["AppVersion"] != appVersion)
{
// 对于更新的 app 来说先要调用这个方法
BackgroundExecutionManager.RemoveAccess();
// 注册后台任务之前先要调用这个方法,并获取 BackgroundAccessStatus 状态
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.DeniedBySystemPolicy || status == BackgroundAccessStatus.DeniedByUser)
{
// 无权限注册后台任务 await new MessageDialog("没有权限注册后台任务").ShowAsync();
}
else
{
// 有权限注册后台任务 ApplicationData.Current.LocalSettings.Values["AppVersion"] = appVersion;
}
} // 用于构造一个后台任务
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = _taskName; // 后台任务的名称
builder.TaskEntryPoint = _taskEntryPoint; // 后台任务入口点,即后台任务的类全名
builder.SetTrigger(applicationTrigger); // 指定后台任务的触发器类型为 ApplicationTrigger(由前台程序通过 api 激活后台任务) // 向系统注册此后台任务
BackgroundTaskRegistration task = builder.Register(); // 为此后台任务增加 Progress 和 Completed 事件监听,以便前台 app 接收后台任务的进度汇报和完成汇报
AttachProgressAndCompletedHandlers(task); _taskRegistered = true; UpdateUI();
} private void btnUnregister_Click(object sender, RoutedEventArgs e)
{
// 遍历所有已注册的后台任务
foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == _taskName)
{
// 从系统中注销指定的后台任务。唯一一个参数代表如果当前后台任务正在运行中,是否需要将其取消
task.Value.Unregister(true);
break;
}
} _taskRegistered = false; UpdateUI();
} private async void btnRequest_Click(object sender, RoutedEventArgs e)
{
// 激活后台任务
await applicationTrigger.RequestAsync();
} private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
{
// 为任务增加 Progress 和 Completed 事件监听,以便前台 app 接收后台任务的进度汇报和完成汇报
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
} private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
{
// 获取后台任务的执行进度
_taskProgress = args.Progress.ToString(); UpdateUI();
} private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
// 后台任务已经执行完成
_taskProgress = "完成"; // 如果此次后台任务的执行出现了错误,则调用 CheckResult() 后会抛出异常
try
{
args.CheckResult();
}
catch (Exception ex)
{
_taskProgress = ex.ToString();
} UpdateUI();
} private async void UpdateUI()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
btnRegister.IsEnabled = !_taskRegistered;
btnUnregister.IsEnabled = _taskRegistered; if (_taskProgress != "")
lblMsg.Text = "进度:" + _taskProgress;
});
}
}
}

OK
[源码下载]

背水一战 Windows 10 (116) - 后台任务: 前台程序激活后台任务的更多相关文章

  1. 背水一战 Windows 10 (115) - 后台任务: 通过 toast 激活后台任务, 定时激活后台任务

    [源码下载] 背水一战 Windows 10 (115) - 后台任务: 通过 toast 激活后台任务, 定时激活后台任务 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 通 ...

  2. 背水一战 Windows 10 (121) - 后台任务: 推送通知

    [源码下载] 背水一战 Windows 10 (121) - 后台任务: 推送通知 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 推送通知 示例演示如何接收推送通知/WebA ...

  3. 背水一战 Windows 10 (119) - 后台任务: 后台下载任务(任务分组,组完成后触发后台任务)

    [源码下载] 背水一战 Windows 10 (119) - 后台任务: 后台下载任务(任务分组,组完成后触发后台任务) 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 后台下 ...

  4. 背水一战 Windows 10 (114) - 后台任务: 后台任务的 Demo(与 app 不同进程), 后台任务的 Demo(与 app 相同进程)

    [源码下载] 背水一战 Windows 10 (114) - 后台任务: 后台任务的 Demo(与 app 不同进程), 后台任务的 Demo(与 app 相同进程) 作者:webabcd 介绍背水一 ...

  5. 背水一战 Windows 10 (120) - 后台任务: 后台上传任务

    [源码下载] 背水一战 Windows 10 (120) - 后台任务: 后台上传任务 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 后台上传任务 示例演示 uwp 的后台上 ...

  6. 背水一战 Windows 10 (118) - 后台任务: 后台下载任务(任务分组,并行或串行执行,组完成后通知)

    [源码下载] 背水一战 Windows 10 (118) - 后台任务: 后台下载任务(任务分组,并行或串行执行,组完成后通知) 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 ...

  7. 背水一战 Windows 10 (117) - 后台任务: 后台下载任务

    [源码下载] 背水一战 Windows 10 (117) - 后台任务: 后台下载任务 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 后台下载任务 示例演示 uwp 的后台下 ...

  8. 背水一战 Windows 10 (103) - 通知(Toast): 基础, 按计划显示 toast 通知

    [源码下载] 背水一战 Windows 10 (103) - 通知(Toast): 基础, 按计划显示 toast 通知 作者:webabcd 介绍背水一战 Windows 10 之 通知(Toast ...

  9. 背水一战 Windows 10 (107) - 通知(Toast): 提示音, 特定场景

    [源码下载] 背水一战 Windows 10 (107) - 通知(Toast): 提示音, 特定场景 作者:webabcd 介绍背水一战 Windows 10 之 通知(Toast) 提示音 特定场 ...

随机推荐

  1. java基础 -- 经典排序

    ----  冒泡排序 方法: 1.每次比较相邻的两个数 2. 小的交换在前面 3.每轮结束后最大的数交换到最后 代码实现: /* * 冒泡排序 * */ public class SortNum { ...

  2. shell执行Python并传参

    shell: python test.py a1 222 test.py import sys print(sys.argv[1], type(sys.argv[1])) # a1 str print ...

  3. spring-boot的Hello World案例,最简单的spring-boot项目

    Spring Boot HelloWorld 一个功能: 浏览器发送hello请求,服务器接收请求并处理,响应Hello World字符串. 1.创建一个maven项目 2.导入依赖spring-bo ...

  4. 【Thread】CountdownEvent任务并行[z]

    System.Threading.CountdownEvent  是一个同步基元,它在收到一定次数的信号之后,将会解除对其等待线程的锁定. CountdownEvent  专门用于以下情况:您必须使用 ...

  5. centos7+mariadb+防火墙,允许远程

    centos7 已安装mariadb,想要允许数据库远程==数据库权限允许+系统允许 mariadb:允许数据库用户在所有ip使用某个用户远程 GRANT ALL PRIVILEGES ON *(数据 ...

  6. Tigase8.0 源代码分析:一、启动篇

    Tigase8.0 引用了IoC(控制反转)和DI(依赖注入) 等技术手段,来对对象的创建和控制.不懂的百度下就知道了,Spring完美的实现IOC ,贴一段解释: 通俗地说:控制反转IoC(Inve ...

  7. 7A - Max Sum

    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. F ...

  8. 20175325 《JAVA程序设计》实验二《JAVA开发环境的熟悉》实验报告

    20175325 <JAVA程序设计>实验二<JAVA开发环境的熟悉>实验报告 一.实验报告封面 课程:Java程序设计 班级:1753班 姓名:石淦铭 学号:20175325 ...

  9. sql server版本、组件和管理工具

    以下信息由何问起收集,希望有帮助. SQL Server 版本 定义 Enterprise 作为高级版本, SQL Server Enterprise 版提供了全面的高端数据中心功能,性能极为快捷.虚 ...

  10. 初学html,任务1:一个简单html页面,要求:内容页面装一篇文章 用html来分段

    这是主要内容部分,用html实现版块分布. 接下来是样式部分. 让页面所有元素的padding和margin都设置为0 : 否则加入一张大的覆盖的背景图片后,会由于浏览器的缘故,图片周边有白边: 设置 ...