Home > C#, WinRT > How to pass arguments to an app activated by a toast notification

How to pass arguments to an app activated by a toast notification

25/03/2013

Toast notifications are a great way to notify the user about the occurrence of events, such as new messages, appointments, deadlines, and so on, even when the app is not running (i.e., using a Background task).

When the user taps or clicks the notification, the associated app is automatically launched, and so its OnLaunched method is invoked. If we want to determine whether the app is activated by a toast notification click, we can use the Arguments property of the LaunchActivatedEventArgs object that is passed to this method.

The toast XML schema defines a launch attribute that contains a string that is passed to the app when it is activated. For example:

<toast launch="launch_arguments">
  <visual version="1">
    <binding template="ToastText02">
      <text id="1">Text Heading</text>
      <text id="2">Text Body</text>
    </binding>
  </visual>
</toast>

When the user clicks such a notification, launch_arguments value is passed to the OnLaunched method as LaunchActivatedEventArgs.Arguments property.

So, it’s easy to determine whether the app is activated by a toast notification. Take a look to the following code:

var toast = ToastContentFactory.CreateToastText02();
toast.TextHeading.Text = "Toast Notification";
toast.TextBodyWrap.Text = "Hello World!";
toast.Launch = "toast://my_arguments";

var notification = toast.CreateNotification();
ToastNotificationManager.CreateToastNotifier().Show(notification);

In this example, we use the Notification Extensions library, that is part of the Windows 8 SDK samples and greatly simplifies the task of creation of tile and toast notifications, avoiding the need to directly manipulate XML templates. To test this code, remeber to set the Toast capable properties in the app manifest to Yes.

On line 4, we have set the Launch property to a string that we can analyze in the OnLaunched method of the app:

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    if (!string.IsNullOrWhiteSpace(args.Arguments))
    {
        var toastLaunch = Regex.Match(args.Arguments, @"^toast://(?<arguments>.*)$");
        var toastActivationArgs = toastLaunch.Groups["arguments"];
        if (toastActivationArgs.Success)
        {
            // The app has been activated through a toast notification click.
            var arguments = toastActivationArgs.Value;

            // ...
        }
    }

    // ...
}

Using a regular expression, we check whether args.Arguments starts with toast:// and, in this case, we extract the actual value, that we can use, for example, to open a page of the app that contains details related to the toast notification.

Note that the content of launch string is defined by the app, so we can use the format we prefer.

Categories: C#, WinRT
Comments are closed.
%d bloggers like this: