WinRT的BackgroundTask

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 sealed
public 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 killed
taskInstance.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 high
switch (BackgroundWorkCost.CurrentBackgroundWorkCost) {
case BackgroundWorkCostValue.Low: // The task can use CPU & network
case BackgroundWorkCostValue.Medium: // The task can use some CPU & network
case 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.exe
TimeTrigger同上,电池也可以1次或多次BackgroundTaskHost.exe
SystemTrigger 1次或多次 BackgroundTaskHost.exe
LocationTrigger进入或离开Geofence多次 BackgroundTaskHost.exe
PushNotificationTrigger收到推送多次BackgroundTaskHost.exe或App自身
ControlChannelTrigger实时通信多次 App







MaintenanceTrigger和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 object
GeofenceMonitor 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 it
Geofence gf = new Geofence("InitialPCLocation", // Geofence Id
new Geocircle(geoposition.Coordinate.Point.Position, 1), // Point & radius
MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited, // When task should run
false, // Not 1 time
TimeSpan.FromSeconds(5), // Dwell time
DateTimeOffset.UtcNow, // Start time
TimeSpan.FromHours(1)); // Duration
gm.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 affected
Geoposition pos = report.Geoposition; // The Geofence object’s position
GeofenceState state = report.NewState; // Entered or Exited
GeofenceRemovalReason 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 support
TaskEntryPoint = typeof(Wintellect.BackgroundTasks.SystemTriggerTask).FullName
};
// Specify the desired trigger (TimeTrigger, MaintenanceTrigger, SystemTrigger,
// LocationTrigger, or PushNotificationTrigger). This example uses a TimeTrigger
btb.SetTrigger(new TimeTrigger(freshnessTime: 60, oneShot: false));
// Optional: add 1+ system conditions and
// indicate whether the task should stop if any condition is lost
btb.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
btb.CancelOnConditionLoss = true; // System tells task to cancel if any condition is lost
// Register the task with Windows
BackgroundTaskRegistration registeredTask = btb.Register();
// Use registeredTask to Unregister, or if the app wants Progress/Completed notifications

资源限额:
注意后台任务不是24小时执行的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值