1

我正在寫一個應用程序,可以在後臺任務中顯示Toast通知(我使用BackgroundTaskBuilder)。在通知中,我使用了兩個按鈕,它應該執行兩個不同的功能,但是我無法獲得通知的響應。在後臺任務中的Toast通知響應

我在網上看到我應該爲此啓動另一個後臺任務,但我無法在後臺任務中啓動另一個後臺任務。

所以我的問題是:我怎樣才能讓用戶點擊通知中的按鈕?

感謝您的幫助。

+0

這看起來可能有用: http://www.kunal-chowdhury.com/2016/02/uwp-tips-toast-button.html –

回答

5

在Windows 10中,我們可以從前臺或後臺處理Toast通知激活。在Windows 10中,它引入了在<action>元素中具有activationType屬性的自適應和交互式敬酒通知。有了這個屬性,我們可以指定這個動作會引起什麼樣的激活。使用下面的吐司例如:

<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

當用戶點擊「查看更多詳細信息」按鈕,它會帶來的應用前景。將使用新的activation kind - ToastNotification調用Application.OnActivated method。我們可以處理這個激活類似以下內容:

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(); 
} 

當用戶點擊「以後提醒我」按鈕,它會觸發激活應用前景的後臺任務來代替。所以不需要在後臺任務中啓動另一個後臺任務。

要處理來自吐司通知的後臺激活,我們需要創建並註冊後臺任務。 後臺任務應在應用程序清單中聲明爲「系統事件」任務,並將其觸發器設置爲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

+0

感謝您的回覆!我明白這一點,但是如果我在後臺任務中創建並顯示通知,我該如何爲'ToastNotificationActionTrigger'啓動另一個? –

+0

@SüliPatrik你需要在[官方示例](https://github.com/WindowsNotifications/quickstart-sending-local-toast-win10)中添加新的後臺任務,如'ToastNotificationBackgroundTask',並註冊'ToastNotificationBackgroundTask'。然後,您可以在原始後臺任務中發送Toast通知。例如,假設您發送一個敬酒,就像官方示例的ButtonSendToast_Click方法一樣。然後當你點擊吐司中的「Like」按鈕時,會觸發'ToastNotificationActionTrigger'。 「ToastNotificationBackgroundTask」將開始。 –

+2

@SüliPatrik您不會在原始後臺任務中啓動'ToastNotificationBackgroundTask',但用戶點擊Toast通知會啓動'ToastNotificationBackgroundTask'並在此後臺任務中,您可以通過使用'details.Argument '。 –