[源码下载]

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

作者:webabcd

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

  • 通过 toast 激活后台任务
  • 定时激活后台任务

示例
1、演示如何通过 toast 激活后台任务
/BackgroundTaskLib/BackgroundTaskToast.cs

/*
* 后台任务,用于演示如何通过 toast 激活后台任务
*
* ToastNotificationActionTriggerDetail - toast 触发器信息
* Argument - 由 toast 传递过来的参数
* UserInput - 由 toast 传递过来的输入框数据
*/ using System;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Notifications; namespace BackgroundTaskLib
{
public sealed class BackgroundTaskToast : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try
{
// 获取 ToastNotificationActionTriggerDetail 对象
ToastNotificationActionTriggerDetail toastDetail = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
if (toastDetail != null)
{
string result = ""; result = "argument: " + toastDetail.Argument;
result += Environment.NewLine; foreach (string key in toastDetail.UserInput.Keys)
{
result += $"key:{key}, value:{toastDetail.UserInput[key]}";
result += Environment.NewLine;
} // 将获取到的 toast 信息保存为文件
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdBackgroundTask\toast.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, result);
}
}
finally
{
deferral.Complete();
}
}
}
}

BackgroundTask/Toast.xaml

<Page
x:Class="Windows10.BackgroundTask.Toast"
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"> <Button Name="buttonShowToast" Content="显示 toast(点击 toast 框或点击 toast 中的按钮则可激活后台任务)" Click="buttonShowToast_Click" Margin="5" /> </StackPanel>
</Grid>
</Page>

BackgroundTask/Toast.xaml.cs

/*
* 演示如何通过 toast 激活后台任务
*
* 注:
* 1、需要引用后台任务项目,相关代码参见 BackgroundTaskLib/BackgroundTaskToast.cs
* 2、需要在 Package.appxmanifest 添加“后台任务”声明,支持的任务类型选择“常规”,并指定 EntryPoint(后台任务的类全名),类似如下:
* <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTaskLib.BackgroundTaskToast">
* <BackgroundTasks>
* <Task Type="general" />
* </BackgroundTasks>
* </Extension>
*
*
* 本例的 toast 的 xml 说明:
* activationType - 通过点击 toast 激活 app 时的激活方式,background 代表后台方式激活
* 其他 toast 的相关知识点请参见:/Notification/Toast/
*/ using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI.Notifications;
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 Toast : Page
{
private string _taskName = "Toast";
private string _taskEntryPoint = "BackgroundTaskLib.BackgroundTaskToast"; public Toast()
{
this.InitializeComponent();
} protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(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;
}
} // 如果任务已注册,则注销
foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> t in BackgroundTaskRegistration.AllTasks)
{
if (t.Value.Name == _taskName)
{
t.Value.Unregister(true);
}
} BackgroundTaskBuilder builder = new BackgroundTaskBuilder
{
Name = _taskName,
TaskEntryPoint = _taskEntryPoint
};
// 指定后台任务的触发器类型为 ToastNotificationActionTrigger(即通过 toast 激活)
builder.SetTrigger(new ToastNotificationActionTrigger());
// 注册后台任务
BackgroundTaskRegistration task = builder.Register();
} // 弹出 toast 通知(点击 toast 框或点击 toast 中的按钮则可激活后台任务)
private void buttonShowToast_Click(object sender, RoutedEventArgs e)
{
string toastXml = @"
<toast activationType='background' launch='launch arguments'>
<visual>
<binding template='ToastGeneric'>
<text>toast - title</text>
<text>toast - content</text>
</binding>
</visual>
<actions>
<input type='text' id='message1' title='title1' />
<action content='确认' activationType='background' arguments='action arguments'/>
</actions>
</toast>"; XmlDocument toastDoc = new XmlDocument();
toastDoc.LoadXml(toastXml); ToastNotification toast = new ToastNotification(toastDoc);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}

2、演示后台任务的应用(定时激活后台任务)
/BackgroundTaskLib/BackgroundTaskTime.cs

/*
* 后台任务,用于演示如何定时激活后台任务
*/ using System;
using Windows.ApplicationModel.Background;
using Windows.Storage; namespace BackgroundTaskLib
{
// 实现 IBackgroundTask 接口,其只有一个方法,即 Run()
public sealed class BackgroundTaskTime : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
// 异步操作
BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try
{
// 写入相关数据到文件
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdBackgroundTask\time.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.AppendTextAsync(file, "background task timeTrigger or maintenanceTrigger: " + DateTime.Now.ToString() + Environment.NewLine); }
finally
{
// 完成异步操作
deferral.Complete();
}
}
}
}

BackgroundTask/Time.xaml

<Page
x:Class="Windows10.BackgroundTask.Time"
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"> <Button Name="btnRegister" Content="注册一个后台任务" Margin="5" Click="btnRegister_Click" />
<Button Name="btnUnregister" Content="注销指定的后台任务" Margin="5" Click="btnUnregister_Click" /> </StackPanel>
</Grid>
</Page>

BackgroundTask/Time.xaml.cs

/*
* 演示后台任务的应用(定时激活后台任务)
*
* 注:
* 1、需要引用后台任务项目,相关代码参见 BackgroundTaskLib/BackgroundTaskTime.cs
* 2、需要在 Package.appxmanifest 添加“后台任务”声明,支持的任务类型选择“计时器”,并指定 EntryPoint(后台任务的类全名),类似如下:
* <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTaskLib.BackgroundTaskTime">
* <BackgroundTasks>
* <Task Type="timer" />
* </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 Time : Page
{
// 所注册的后台任务的名称
private string _taskName = "Time"; // 所注册的后台任务的 EntryPoint,即后台任务的类全名
private string _taskEntryPoint = "BackgroundTaskLib.BackgroundTaskTime"; // 后台任务是否已在系统中注册
private bool _taskRegistered = false; public Time()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 遍历所有已注册的后台任务
foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == _taskName)
{
_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()
{
Name = _taskName,
TaskEntryPoint = _taskEntryPoint };
// 指定后台任务的触发器类型为 MaintenanceTrigger(定时激活,最小周期 15 分钟)
builder.SetTrigger(new MaintenanceTrigger(, false));
// 注册后台任务
BackgroundTaskRegistration task = builder.Register(); _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 UpdateUI()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
btnRegister.IsEnabled = !_taskRegistered;
btnUnregister.IsEnabled = _taskRegistered;
});
}
}
}

OK
[源码下载]

背水一战 Windows 10 (115) - 后台任务: 通过 toast 激活后台任务, 定时激活后台任务的更多相关文章

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

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

  2. 背水一战 Windows 10 (106) - 通知(Toast): 通过 toast 打开协议, 通过 toast 选择在指定的时间之后延迟提醒或者取消延迟提醒

    [源码下载] 背水一战 Windows 10 (106) - 通知(Toast): 通过 toast 打开协议, 通过 toast 选择在指定的时间之后延迟提醒或者取消延迟提醒 作者:webabcd ...

  3. 背水一战 Windows 10 (105) - 通知(Toast): 带按钮的 toast, 带输入的 toast(文本输入框,下拉选择框)

    [源码下载] 背水一战 Windows 10 (105) - 通知(Toast): 带按钮的 toast, 带输入的 toast(文本输入框,下拉选择框) 作者:webabcd 介绍背水一战 Wind ...

  4. 背水一战 Windows 10 (104) - 通知(Toast): 纯文本 toast, 短时 toast, 长时 toast, 图文 toast

    [源码下载] 背水一战 Windows 10 (104) - 通知(Toast): 纯文本 toast, 短时 toast, 长时 toast, 图文 toast 作者:webabcd 介绍背水一战 ...

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

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

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

    [源码下载] 背水一战 Windows 10 (116) - 后台任务: 前台程序激活后台任务 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 前台程序激活后台任务 示例演示后 ...

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

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

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

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

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

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

随机推荐

  1. VBA读写ini 配置文件

    Option Explicit 'read Private Declare Function GetPrivateProfileString Lib "kernel32" Alia ...

  2. js中的回调函数 和promise解决异步操作中的回调地狱问题。

    回调函数 : 函数作为参数传递到另外一个函数中.简单数据类型和引入数据类型中的数组和对象作为参数传递大家肯定都不陌生,其实引用数据类型中的函数也是可以的. 事实上大家见到的很多,用到的也很多,比如jQ ...

  3. mac sublime3 无法安装Package Control

    一.在线安装 1.打开sublime,Ctrl+` 打开控制台, 输入 import urllib.request,os,hashlib; h = '6f4c264a24d933ce70df5dedc ...

  4. EasyPR源码剖析(2):车牌定位

    上一篇主要介绍了车牌识别的整体框架和流程,车牌识别主要划分为了两个过程:即车牌检测和字符识别,而车牌识别的核心环节就是这一节主要介绍的车牌定位,即 Plate Locate.车牌定位主要是将图片中有可 ...

  5. python基础之Day17

    一.包 1.包 含有--init--.py的文件夹  是模块的一种形式 本质是一个文件夹(用来存放文件,包内所有的文件都是用来被导入的) import 包 包.名字     往包的init里加名字 导 ...

  6. java之路 定义个一初始值 取它 个位 十位 百位 千位。。的数值。

    class Demo{ public static void main(String[] args){ int i =2584; //do{ int g = i%10; int s = (i%100) ...

  7. Chapter4_控制执行流程

    总结java中所有的与流程控制有关的知识 (1)表达式判断 Java中只允许true或者false来作为判断条件,不允许用0或者非0值作为判断条件. (2)if-else 与流程密切相关的语句,决定了 ...

  8. AJAX随笔2

    Ajax作用: 是用JavaScript向服务器发送异步请求,然后服务器给出响应,然后以XML格式的文件返回给浏览器端! 异步: 当浏览器向服务器发送请求的时候,不是整个页面刷新,而是局部刷新[局部信 ...

  9. vue,react,angular

    一.Vue.js:     其实Vue.js不是一个框架,因为它只聚焦视图层,是一个构建数据驱动的Web界面的库.     Vue.js通过简单的API(应用程序编程接口)提供高效的数据绑定和灵活的组 ...

  10. python微信自动回复

    模块是itchat 下载:命令行输入 pip install itchat import itchat #导入itchat模块 itchat.auto_login() #登陆微信,授权 用命令行发送给 ...