I\'m writing an application which can show toast notifications in a background task (I use BackgroundTaskBuilder). In the notification I\'m using two button, which
In Windows 10, we can handle a toast notification activation from either foreground or background. In Windows 10, it introduces adaptive and interactive toast notifications which have an activationType
attribute in <action>
element. With this attribute, we can specify what kind of activation this action will cause. Using following toast for example:
<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>
When user clicks "See more details" button, it will bring the app to foreground. Application.OnActivated method will be invoked with a new activation kind – ToastNotification. And we can handle this activation like following:
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();
}
When user clicks "Remind me later" button, it will trigger a background task instead of activating the foreground app. So there is no need to start another background task in a background task.
To handle the background activation from toast notifications, we need to create and register a background task. The background task should be declared in app manifest as "System event" task and set its trigger to ToastNotificationActionTrigger. Then in the background task, use ToastNotificationActionTriggerDetail to retrieve pre-defined arguments to determine which button is clicked like:
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
}
}
}
For more info, please see Adaptive and interactive toast notifications, especially Handling activation (foreground and background). And also the complete sample on GitHub.