后台任务中的Toast通知响应

时间:2016-11-17 11:08:24

标签: uwp win-universal-app windows-10-universal toast background-task

我正在编写一个可以在后台任务中显示Toast通知的应用程序(我使用BackgroundTaskBuilder)。在通知中我使用了两个按钮,它应该执行两个不同的功能,但我无法获得通知的响应。

我在网上看到我应该为此开始另一个后台任务,但是我无法在后台任务中启动另一个后台任务。

所以我的问题是:如何让用户在通知中点击哪个按钮?

感谢您的帮助。

1 个答案:

答案 0 :(得分:7)

在Windows 10中,我们可以处理来自前台或后台的Toast通知激活。在Windows 10中,它引入了在activationType元素中具有<action>属性的自适应和交互式Toast通知。使用此属性,我们可以指定此操作将导致的激活类型。例如使用以下吐司:

<toast launch="app-defined-string">
  <visual>
    <binding template="ToastGeneric">
      <text>Microsoft Company Store</text>
      <text>New Halo game is back in stock!</text>
    </binding>
  </visual>
  <actions>
    <action activationType="foreground" content="See more details" arguments="details"/>
    <action activationType="background" content="Remind me later" arguments="later"/>
  </actions>
</toast>

enter image description here

当用户点击“查看更多详细信息”按钮时,它会将应用程序置于前台。将使用新的Application.OnActivated method - activation kind调用ToastNotification。我们可以像下面这样处理这种激活:

protected override void OnActivated(IActivatedEventArgs e)
{
    // Get the root frame
    Frame rootFrame = Window.Current.Content as Frame;

    // TODO: Initialize root frame just like in OnLaunched

    // Handle toast activation
    if (e is ToastNotificationActivatedEventArgs)
    {
        var toastActivationArgs = e as ToastNotificationActivatedEventArgs;

        // Get the argument
        string args = toastActivationArgs.Argument;
        // TODO: Handle activation according to argument
    }
    // TODO: Handle other types of activation

    // Ensure the current window is active
    Window.Current.Activate();
}

当用户点击“稍后提醒我”按钮时,它将触发后台任务,而不是激活前台应用。因此,无需在后台任务中启动另一个后台任务。

要处理来自Toast通知的后台激活,我们需要创建并注册后台任务。该 后台任务应在应用程序清单中声明为“系统事件”任务,并将其触发器设置为ToastNotificationActionTrigger。然后在后台任务中,使用ToastNotificationActionTriggerDetail检索预定义的参数以确定单击哪个按钮:

public sealed class NotificationActionBackgroundTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;

        if (details != null)
        {
            string arguments = details.Argument;
            // Perform tasks
        }
    }
}

有关详细信息,请参阅Adaptive and interactive toast notifications,尤其是Handling activation (foreground and background)。还有GitHub上的the complete sample

相关问题