Run in the background indefinitely

不发布在Microsoft Store的App(个人的,或者企业的)可以在后台持续运行。 在Win10 1703中,提供了API可以关闭幕后以及会话延展的资源控制。

简单地说,就是通过一个受控能力来关闭操作系统的操控行为:

<Package
    ...
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="uap mp rescap">
  ...
  <Capabilities>
    <rescap:Capability Name="extendedExecutionUnconstrained"/>
  </Capabilities>
</Package>

Trigger a background task from within your app

使用ApplicationTrigger来在应用内触发幕后任务。

如果你的App有任务交给幕后去完成,那么ApplicationTrigger 是一个合适的选中。当前台关闭额时候,任务依然可以运行。

如何任务跟前台的状态相关联,那么Extended Execution可能是更好的选择。

创建一个ApplicationTrigger:

// _AppTrigger is an ApplicationTrigger field defined at a scope that will keep it alive
// as long as you need to trigger the background task.
// Or, you could create a new ApplicationTrigger instance and use that when you want to
// trigger the background task.
Windows::ApplicationModel::Background::ApplicationTrigger _AppTrigger;

添加一个执行条件:

Windows::ApplicationModel::Background::SystemCondition internetCondition{
    Windows::ApplicationModel::Background::SystemConditionType::InternetAvailable };

SystemConditionType列出了可用的条件类型。

调用RequestAccessAsync来检查用户允许的幕后任务级别。

用户可以禁止后台任务,查看Optimize background activity

注册幕后任务:

std::wstring entryPoint{ L"Tasks.ExampleBackgroundTaskClass" };
std::wstring taskName{ L"Example application trigger" };

Windows::ApplicationModel::Background::BackgroundTaskRegistration task{
    RegisterBackgroundTask(entryPoint, taskName, appTrigger, internetCondition) };

触发幕后任务前,需要保证任务已经被注册,可以使用 BackgroundTaskRegistration来验证这一点。一个好的时机是在应用启动的时候检查。

ApplicationTrigger.RequestAsync.用来在App内启动幕后任务。注意,这个API不能再幕后任务中调用(当App进入后台的时候也不行)。如果用户给幕后任务设置了限制,那么这个API可能返回DisabledByPolicy 。一次只能运行一个实例,否则会返回CurrentlyRunning.。

查看Optimize background activity来学习如何优化幕后任务的资源使用。

通过Memory Management APIs 可以管理幕后任务所用资源。

另外,应用触发的幕后任务大概只能运行10分钟。

Debug a background task

(略)

(本篇完)