[源码下载]

背水一战 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. [Mysql]一些知识点

    Mysql引擎类型 InnoDB: 行级锁->写性能略优:支持事务 MYISAM: 表级锁->读性能优:不支持事务 表示时间的类型 datetime 可表示时间范围大 1000-9999. ...

  2. Linux下普通IO文件操作函数---C语言

    普通文件IO总结 FILE结构体    typedef struct   {       int level; /*填充/清空一级缓存*/     unsigned flag; /*文件状态指针*/ ...

  3. Hillstone目的地址转换DNAT配置

    目的地址映射主要用于将内网的服务器对外进行发布(如http服务,ftp服务,数据库服务等),使外网用户能够通过外网地址访问需要发布的服务. 常用的DNAT映射有一对一IP映射,一对一端口映射,多对多端 ...

  4. 批量替换表中某字段的“\t”

    update dbo.Hishop_Products set [Description]=replace(cast([Description] as varchar(8000)),' ',' ')

  5. Java多线程02(线程安全、线程同步、等待唤醒机制)

    Java多线程2(线程安全.线程同步.等待唤醒机制.单例设计模式) 1.线程安全 如果有多个线程在同时运行,而这些线程可能会同时运行这段代码.程序每次运行结果和单线程运行的结果是一样的,而且其他的变量 ...

  6. linklist和arraylist区别

    ArrayList更适合读取数据,linkedList更多的时候添加或删除数据.

  7. docker-compose使用

    1.创建app.py项目文件,执行以下代码 import time import redis from flask import Flask app = Flask(__name__) cache = ...

  8. [并查集][NOIP2015]信息传递

    信息传递 题目描述 有 N 个同学( 编号为 1 到 N) 正在玩一个信息传递的游戏. 在游戏里每人都有一个固定的信息传递对象, 其中,编号为i的同学的信息传递对象是编号为ti的同学. 游戏开始时, ...

  9. java 判断null和空

    判断null和空 org.apache.commons.lang3 if(StringUtils.isBlank(valuationMeasureUnitName)){ }

  10. 八、pyqt5按钮类控件——QPushButton、QRadioButton、QCheckBox

    pyqt5中常用的按钮类控件有QPushButton.QRadioButton.QCheckBox.QToolButton等.这些按钮类的基类都是QAbstracButton类.所以这些类有部分方法是 ...