后台任务中的Toast通知响应

Sül*_*rik 2 toast win-universal-app background-task uwp windows-10-universal

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

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

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

谢谢您的帮助.

Jay*_*Zuo 7

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

<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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当用户单击"查看更多详细信息"按钮时,它会将应用程序置于前台.Application.OnActivated方法将使用新的调用激活样 - 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();
}
Run Code Online (Sandbox Code Playgroud)

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

要处理来自Toast通知的后台激活,我们需要创建并注册后台任务.后台任务应在app manifest中声明为"System event"任务,并将其触发器设置为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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅自适应和交互式Toast通知,尤其是处理激活(前台和后台).还有GitHub上的完整示例.

  • @SüliPatrik您需要在[官方示例](https://github.com/WindowsNotifications/quickstart-sending-local-toast-win10)中添加新的后台任务,例如“ToastNotificationBackgroundTask”,并注册“ToastNotificationBackgroundTask”。然后您可以在原来的后台任务中发送 toast 通知。例如,假设您发送一个 toast,就像官方示例的“ButtonSendToast_Click”方法中的那样。然后,当您点击 toast 中的“Like”按钮时,将会触发 `ToastNotificationActionTrigger`。`ToastNotificationBackgroundTask` 将启动。 (2认同)
  • @SüliPatrik你没有在原始后台任务中启动`ToastNotificationBackgroundTask`,但是用户点击toast通知会启动`ToastNotificationBackgroundTask`,在这个后台任务中,你可以通过使用`details.Argument`知道哪个按钮用户点击了. (2认同)