WinRT的BackgroundTask
来源:互联网 发布:剑三好看的纯阳脸数据 编辑:程序博客网 时间:2024/04/29 14:23
BackgroundTask与主进程是不同的进程,所以BackgroundTask不能更新主UI,但是可以更新tile,发toast消息和读写文件。
至少要执行一次主进程以激活BackgroundTask。
实现步骤:
1,实现后台任务的逻辑代码,必须是一个WinRt Component,例如:
namespace MyApp.BackgroundTasks { // NOTE: determines filename "MyApp.BackgroundTasks.WinMD"using Windows.ApplicationModel.Background; // For IBackgroundTask & IBackgroundTaskInstance// NOTE: WinRT components MUST be public and sealedpublic sealed class MyBackgroundTask : IBackgroundTask {public void Run(IBackgroundTaskInstance taskInstance) {// Register cancelation handler (see the "Background task cancellation" section)// NOTE: Once canceled, a task has 5 seconds to complete or the process is killedtaskInstance.Canceled +=(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) => {// TODO: Tell task it should cancel itself as soon as possible...};// Recommended: Adjust task behavior based on CPU and network availability// For example: A mail app could download mail for all folders when cost is// low and only download mail for the Inbox folder when cost is highswitch (BackgroundWorkCost.CurrentBackgroundWorkCost) {case BackgroundWorkCostValue.Low: // The task can use CPU & networkcase BackgroundWorkCostValue.Medium: // The task can use some CPU & networkcase BackgroundWorkCostValue.High: // The task should avoid using CPU & network// This example records the last trigger time in an application data setting// so the app can read it later if it chooses. We do regardless of work cost.ApplicationData.Current.LocalSettings.Values["LastTriggerTime"] =DateTimeOffset.Now;break;}}}}把逻辑写在IBackgroundTask接口的Run函数中。
2,决定使用哪个触发器
后台任务只有在某个条件触发后才会执行。这些触发器包括:
Trigger触发条件频率是否需要锁屏宿主进程MaintenanceTrigger交流电每15分钟一次1次或多次 BackgroundTaskHost.exeTimeTrigger同上,电池也可以1次或多次是BackgroundTaskHost.exeSystemTrigger 1次或多次 BackgroundTaskHost.exeLocationTrigger进入或离开Geofence多次 BackgroundTaskHost.exePushNotificationTrigger收到推送多次是BackgroundTaskHost.exe或App自身ControlChannelTrigger实时通信多次 AppMaintenanceTrigger和TimeTrigger每天最多执行96次(每15分钟)。可以配置让他们只执行一次。
MaintenanceTrigger用于执行不急的任务,比如更新推送,更新tile,发toast,原始推送等。
TimeTrigger用于执行紧急的任务,比如检查邮件。
SystemTrigger在某些系统事件触发时执行,比如:
- 当连上网时,
- 网络状态切换时(3G/WiFi),
- 安装新版本的App时,
- 登陆的微软账户变化时,
- 时区改变时,
- 收到短信时,
- App被添加到锁屏桌面时
- App从锁屏桌面移除时
- 后台任务的性能成本变化时
- 用户从离开变成回来(输入)时
- 用户从活跃到离开时(4分钟无输入)
- 用户登陆时
- 网络连接被重置需要重新连接时
LocationTrigger用于当用户进入某个区域时提示团购之类的信息。比如:
private async Task InitializeGeofenceMonitorAsync() {// Get a reference to the app's singleton GeofenceMonitor objectGeofenceMonitor gm = GeofenceMonitor.Current;gm.Geofences.Clear(); // Erase all its Geofence objects// Get the PC's current location (requires Location capability)Geoposition geoposition = await new Geolocator().GetGeopositionAsync();// Register a Geofence whose state changes whenever the PC goes within 1 meter of itGeofence gf = new Geofence("InitialPCLocation", // Geofence Idnew Geocircle(geoposition.Coordinate.Point.Position, 1), // Point & radiusMonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited, // When task should runfalse, // Not 1 timeTimeSpan.FromSeconds(5), // Dwell timeDateTimeOffset.UtcNow, // Start timeTimeSpan.FromHours(1)); // Durationgm.Geofences.Add(gf); // Add the Geofence object to the GeofenceMonitor's collection}
public sealed class GeofenceLocationTask : IBackgroundTask {public void Run(IBackgroundTaskInstance taskInstance) {IReadOnlyList<GeofenceStateChangeReport> reports = GeofenceMonitor.Current.ReadReports();foreach (GeofenceStateChangeReport report in reports) {// This loop processes a report for each Geofence object that changed// Each report includes the Geofence object affected, its position,// the NewState of the Geofence (Entered or Exited), and the reason why// the report was generated (Used or Expired):Geofence geofence = report.Geofence; // The Geofence object affectedGeoposition pos = report.Geoposition; // The Geofence object’s positionGeofenceState state = report.NewState; // Entered or ExitedGeofenceRemovalReason reason = report.RemovalReason; // Used or Expired// TODO: Process the Geofence object affected here...}}}
PushNotificationTrigger用于实时通信的应用,比如邮件,IM,VOIP。应用必须被添加到锁屏。
ControlChannelTrigger也用实时通信的应用,当低电量时也可以工作。当连接着socket的时候,用于legacy的通信协议。
3,添加manifest声明
Executable字段,一般留空。
Entry Point字段指定类名(包括namespace)
注意:锁屏App可以在低电量时运行
4,注册BackgroundTask
var btb = new BackgroundTaskBuilder {Name = "Some friendly name", // See the "Debugging background tasks" section// Specify the full name of the class implementing the IBackgroundTask interface// You could specify a literal string here, but I prefer to do it this// way to get compile-time safety and rename refactoring supportTaskEntryPoint = typeof(Wintellect.BackgroundTasks.SystemTriggerTask).FullName};// Specify the desired trigger (TimeTrigger, MaintenanceTrigger, SystemTrigger,// LocationTrigger, or PushNotificationTrigger). This example uses a TimeTriggerbtb.SetTrigger(new TimeTrigger(freshnessTime: 60, oneShot: false));// Optional: add 1+ system conditions and// indicate whether the task should stop if any condition is lostbtb.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));btb.CancelOnConditionLoss = true; // System tells task to cancel if any condition is lost// Register the task with WindowsBackgroundTaskRegistration registeredTask = btb.Register();// Use registeredTask to Unregister, or if the app wants Progress/Completed notifications
资源限额:
注意后台任务不是24小时执行的。
0 0
- WinRT的BackgroundTask
- backgroundTask
- openURL(注意backgroundTask 的学习)
- WinRT的IBuffer
- WinRT的 HttpClient
- WinRT的HttpBaseProtocolFilter类
- WinRT的Socket
- about backgroundTask
- WinRT
- Win8与WinRt的区别
- WinRT的存储对象模型
- WinRT的Stream对象模型
- 【Windows8开发】关于WinRT组件,WinRT dll,Win32 dll,WinRT exe组件的一些尝试
- WinRT:Win32的面向对象替代品
- WinRT:Win32的面向对象替代品
- WinRT:Win32的面向对象替代品
- 微软WinRT开发人员的一些解答
- WinRT开发语言的功能和效率
- 从一个程序员笑话看软件开发管理
- 计算输入数字的个数
- POJ-1308 并查集
- 3.18 通过http访问服务器
- WifiStateMachine状态机结构说明
- WinRT的BackgroundTask
- [CentOS]压缩+解压+打包命令大全
- FusionCharts使用问题及解决方法(一)-FusionCharts常见问题大全
- 关于软件测试的几点反思 - 测试工作的三个阶段
- CURL处理跨域Cookies
- 透明效果
- 统计一个大小为30kb~300kb的文本中各单词出现的频率,并输出前十个单词和进行程序性能分析
- c++ 复制文件夹及其内所有子文件内容
- LeetCode Permutations