使用后台任务响应系统事件

重要的 API

了解如何创建响应 SystemTrigger 事件的后台任务。

本主题假定你已经为你的应用编写了一个后台任务类,并且需要运行该任务以响应系统触发的某个事件(如 Internet 可用性发生改变或用户登录时)。 此主题重点介绍 SystemTrigger 类。 有关编写后台任务类的详细信息可以在创建和注册进程内后台任务创建和注册进程外后台任务中找到。

创建 SystemTrigger 对象

在应用代码中,创建一个新的 SystemTrigger 对象。 第一个参数 triggerType 指定了将激活此后台任务的系统事件触发器的类型。 有关事件类型的列表,请参阅 SystemTriggerType

第二个参数 OneShot 指定后台任务是否在下次发生系统事件时,或在每次发生系统事件时仅运行一次,直至任务注销为止。

以下代码指定当 Internet 变为可用时运行后台任务:

SystemTrigger internetTrigger = new SystemTrigger(SystemTriggerType.InternetAvailable, false);
Windows::ApplicationModel::Background::SystemTrigger internetTrigger{
    Windows::ApplicationModel::Background::SystemTriggerType::InternetAvailable, false};
SystemTrigger ^ internetTrigger = ref new SystemTrigger(SystemTriggerType::InternetAvailable, false);

注册后台任务

通过调用后台任务注册函数注册后台任务。 有关注册后台任务的详细信息,请参阅注册后台任务

以下代码将为在进程外运行的后台进程注册后台任务。 如果要调用在与主机应用相同的进程中运行的后台任务,请不要设置 entrypoint

string entryPoint = "Tasks.ExampleBackgroundTaskClass"; // Namespace name, '.', and the name of the class containing the background task
string taskName   = "Internet-based background task";

BackgroundTaskRegistration task = RegisterBackgroundTask(entryPoint, taskName, internetTrigger, exampleCondition);
std::wstring entryPoint{ L"Tasks.ExampleBackgroundTaskClass" }; // don't set for in-process background tasks.
std::wstring taskName{ L"Internet-based background task" };

Windows::ApplicationModel::Background::BackgroundTaskRegistration task{
    RegisterBackgroundTask(entryPoint, taskName, internetTrigger, exampleCondition) };
String ^ entryPoint = "Tasks.ExampleBackgroundTaskClass"; // don't set for in-process background tasks
String ^ taskName   = "Internet-based background task";

BackgroundTaskRegistration ^ task = RegisterBackgroundTask(entryPoint, taskName, internetTrigger, exampleCondition);

注意

通用 Windows 平台应用必须在注册任何后台触发器类型之前调用 RequestAccessAsync

若要确保通用 Windows 应用在你发布更新后继续正常运行,必须在启动已经过更新的应用时调用 RemoveAccess,然后调用 RequestAccessAsync。 有关详细信息,请参阅后台任务指南

注意

后台任务注册参数在注册时验证。 如果有任何注册参数无效,则会返回一个错误。 确保你的应用能够流畅地处理后台任务注册失败的情况,否则,如果你的应用依赖于在尝试注册任务后具备有效注册对象,则它可能会崩溃。  

注解

若要实际查看后台任务注册,请下载后台任务示例

可运行后台任务以响应 SystemTriggerMaintenanceTrigger 事件,但你仍需要 在应用程序清单中声明后台任务。 还必须在注册任何后台任务之前调用 RequestAccessAsync

应用可以注册响应 TimeTriggerPushNotificationTriggerNetworkOperatorNotificationTrigger 事件的后台任务,从而使这些事件可以提供与用户的实时通信,即使该应用不在前台也是如此。 有关详细信息,请参阅使用后台任务支持应用