Search code examples
c#uwptoastbackground-taskclickevent

Set an event on ToastButton from background task


From a UWP application I start this background task:

namespace Background.UWP
{
    public sealed class BackgroundTask : IBackgroundTask
    {
        private WatchLoop _watchLoop;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            ApplicationTriggerDetails details = taskInstance.TriggerDetails as ApplicationTriggerDetails;
            var arg = details.Arguments["MyArg"].ToString();

            // Start a loop that periodically does some checks 
            // and, if necessary, displays a toast with button "Show Details".
            _watchLoop = new WatchLoop(arg, new ToastNotification());
            _watchLoop.Start();    
        }    
    }
}

Class ToastNotification is defined as follows:

namespace Background.UWP
{
    internal class ToastNotification : IToastNotification
    { 
        public bool Show(string message)
        {
            var button = new ToastButton()
              .SetContent("Anzeigen")
              .AddArgument("action", "reply")
              .SetBackgroundActivation();

            var toast = new ToastContentBuilder();
            toast.AddArgument("action", "viewConversation")
             .AddArgument("conversationId", 9813)
             .AddText(message)
             .AddButton(button);
            toast.Show();
            return false;
        }    
    }
}

Somewhere in my WhatchLoop code I call method Show();

Now I don't know where to register the click event on button. Here I found that I have to implement OnActivated in App.xaml.cs. However, because the toast is displayed by a background task, I don't have App.xaml.cs.

What should I do?

Edit: BackgroundTask runs in a separate Windows Runtime Component.


Solution

  • I found a simple solution for my purpose:

    Just add these lines:

    Uri uri = new Uri("myapp://<application>");
    button.SetProtocolActivation(uri);
    

    The only thing I'll have to find out is how the <application> URL has to be formed. (See this question.)