Action Center Notifications In Universal Windows Programs - Part Three

Before reading this article, I highly recommend reading the previous parts of the series.

In Windows 10 Anniversary update, Microsoft has allowed context menu features in the Action Center. The application can give more options to the user to get the specific input  and one more advantage for this is that without activating a foreground app, we can process the input into the background.

Note: This article has a required background task concept knowledge, if you don’t have any idea about the Background task, I highly recommend you read the BackgroundTask complete series.

Context menu Default menu 

The image, given below, with default context menu, is available in the Action Center for all the Applications notifications. If app contains a custom context menu, it will be placed on the top of the menu.

 

Overall concept 
  1. Any notification will create the Action Center notification toast message with the custom action menu.
  2. To create a custom menu, the menu prepares with the Background or Foreground activation type.
  3. If the custom menu contains a background type, register the ToastNotificationAction TriggerDetails background task to handle the background task request. 
  4. Foreground activation is required to type launch the Application. 
Quick Overview BackgroundTask implementation of Time Zone
 
In this example, background task has implemented into the single process model.
 
TimerZone event has registered.
  1. public void IsTimeClassRegister()  
  2.        {  
  3.            var bgTimerReg = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);  
  4.            var bgTimeTask = HandlingBgTask.CreateBgTask("TimerRegister""BGProcess.BgTask", bgTimerReg);  
  5.            if (bgTimeTask != null) bgTimeTask.Completed += BgTask_Completed;  
  6.        }  

Note

HandlingBgTask is a user defined class source code, which is available at the end of the article.

Trigger the ToastNotification (More details in the next section) into the Run method.
  1. public static void RunBackGroundTask(IBackgroundActivatedEventArgs args)  
  2.         {  
  3.             var bgInstance = args.TaskInstance;  
  4.             if (bgInstance == nullreturn;  
  5.             _appServiceDeferral = bgInstance.GetDeferral();  
  6.             bgInstance.Canceled += BgInstance_Canceled;  
  7.             HandlingMenu();  
  8.             _appServiceDeferral.Complete(); }  
Activate Background Task into Single Process Modal. 
  1. protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)  
  2.        {  
  3.            RunBackGroundTask(args);  
  4.        }   
Microsoft. Toolkit. Uwp.Notifications Tool kit

As we have seen previous articles that ToastNotification has updated by making a use of XML template, instead of the template. In this article, we are going to use the UWPToolkit to create toast notification.

Install UWP toolkit

Go to Manage NuGet Packages for the solutions -> go to Browse -> Search “Microsoft.Toolkit.Uwp.Notifications” & Install.

 
Ex

Its id is used to change the Window Title bar color, which is based on the user input, which is clicked by the Action Center context menu.

ToastContextMenuItem

ToastContextMenuItem class is used to create the context menu. Three properties are used to create a menu item, which are shown below.

  1. Name of the context menu
  2. Arguments (Input) to the application.
  3. Activation type.

Menu click ActivationType: ActivationType property is used to how the Application should react, which is based on the menu click activated.

  • Background
    Execute the code into the background task and the user interaction is not required.

  • Foreground
    Default behavior, where an Application is launched.

  • Protocol
    Launch the different Application.

Create Context Menu & Menu handing code

Create a Context menu function, as shown below.

  1. public static ToastContextMenuItem CreateMenuItem(string menuName, string args,ToastActivationType activationType)  
  2.         {  
  3.             ToastContextMenuItem menuItem = new ToastContextMenuItem(menuName, args)  
  4.             {  
  5.                 ActivationType = activationType  
  6.             };  
  7.   
  8.             return menuItem;  
  9.         }  
Create Menu command with Background ActivationType & show the ToastNofitication in the ActionCenter. This function is called when the Time Zone event has occurred.  
  1. public static void HandlingMenu()  
  2.         {  
  3.             var toastCustom = new ToastActionsCustom()  
  4.             {  
  5.                 ContextMenuItems =  
  6.                 {  
  7.                     CreateMenuItem("Red""1",ToastActivationType.Background),  
  8.                     CreateMenuItem("Green""2",ToastActivationType.Background),  
  9.                     CreateMenuItem("Blue""3",ToastActivationType.Background)  
  10.                 }  
  11.             };  
  12.   
  13.             var tostVisual = new ToastVisual { BindingGeneric = new ToastBindingGeneric() };  
  14.   
  15.             var toastMenu = new ToastContent  
  16.             {  
  17.                 Visual = tostVisual,  
  18.                 Actions = toastCustom  
  19.             };  
  20.             ToastNotification toastNotification = new ToastNotification(toastMenu.GetXml());  
  21.             ToastNotificationManager.CreateToastNotifier().Show(toastNotification);  
  22.         }  
Handle the Menu command

ToastNotificationActionTriggerDetail arguments : It is required to find which contextmenu command is triggered by the user.
  1. private static async void ExecuteMenuCmd(ToastNotificationActionTriggerDetail toatInfo)  
  2.         {  
  3.             if (toatInfo == nullreturn;  
  4.             var cmdId = Convert.ToInt32(toatInfo.Argument);  
  5.   
  6.             switch (cmdId)  
  7.             {  
  8.                 case 1:  
  9.                     _toastColor = Colors.Red;  
  10.                     break;  
  11.                 case 2:  
  12.                     _toastColor = Colors.Green;  
  13.                     break;  
  14.                 case 3:  
  15.                     _toastColor = Colors.Blue;  
  16.                     break;  
  17.             }  
  18.             var strColor = _toastColor.ToString();  
  19.             var dialog = new MessageDialog("You Clicked " + strColor, "Information");  
  20.             await dialog.ShowAsync();  
  21.         }  
Register ToastNotificationActionTrigger as BackgroundTask  
 
If the custom menu has implemented as Background activation type, we have to register ToastNotificationActionTrigger as a background task, so that we can handle the ToastNotification. 
  1. public void IsToastClassRegister()  
  2.         {  
  3.             var bgToastReg = new ToastNotificationActionTrigger();  
  4.             var bgToastTask = HandlingBgTask.CreateBgTask("ToastRegister""BGProcess.BgTask1", bgToastReg);  
  5.             if (bgToastTask != null) bgToastTask.Completed += BgToastTask_Completed;  
  6.         }  
In the same Run ( defined into the previous section) method, we can use and handle the Toast notification. Also, small changes need to be done in Run method, Check the TriggerDetails; if it is ToastNotificationActionTriggerDetail it calls to ToastNotification code, else call the create ToastNotification code. 
  1. public static void RunBackGroundTask(IBackgroundActivatedEventArgs args)  
  2.         {  
  3.             var bgInstance = args.TaskInstance;  
  4.             if (bgInstance == nullreturn;  
  5.             _appServiceDeferral = bgInstance.GetDeferral();  
  6.             bgInstance.Canceled += BgInstance_Canceled;  
  7.             var bgTaskInstance = bgInstance.TriggerDetails as ToastNotificationActionTriggerDetail;  
  8.   
  9.             if (bgTaskInstance != null)  
  10.             {  
  11.                 ExecuteMenuCmd(bgTaskInstance);  
  12.             }  
  13.             else  
  14.             {  
  15.                HandlingMenu();  
  16.             }  
  17.             _appServiceDeferral.Complete();  
  18.         }  
Leave Background & Update the titleBar color. 
  1. private void Current_LeavingBackground(object sender, LeavingBackgroundEventArgs e)  
  2.         {  
  3.             var titleBar = ApplicationView.GetForCurrentView().TitleBar;  
  4.             titleBar.BackgroundColor = _toastColor;        }   

Handling BG Task code is shown.
  1. public static class HandlingBgTask  
  2.     {  
  3.         private static IBackgroundTaskRegistration _backgroundTask;  
  4.   
  5.         private static IBackgroundTrigger _setTrigger;  
  6.   
  7.         public static IBackgroundTaskRegistration CreateBgTask(string bgTaskName, string bgEntryPoint,  
  8.             IBackgroundTrigger bgTigger)  
  9.         {  
  10.             _setTrigger = bgTigger;   
  11.             _backgroundTask = RegisterBgTask(bgTaskName);  
  12.             return _backgroundTask;  
  13.         }  
  14.   
  15.         private static async Task<bool> IsAppHasPermission()  
  16.         {  
  17.             var bgStatus = await BackgroundExecutionManager.RequestAccessAsync();  
  18.             return IsBackgroundAccessValid(bgStatus);  
  19.         }  
  20.   
  21.         private static bool IsBackgroundAccessValid(BackgroundAccessStatus bgStatus)  
  22.         {  
  23.             var status = default(bool);  
  24.             switch (bgStatus)  
  25.             {  
  26.                 case BackgroundAccessStatus.DeniedBySystemPolicy:  
  27.                 case BackgroundAccessStatus.DeniedByUser:  
  28.                     break;  
  29.                 case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:  
  30.                 case BackgroundAccessStatus.AlwaysAllowed:  
  31.                     status = true;  
  32.                     break;  
  33.             }  
  34.             return status;  
  35.         }  
  36.   
  37.         private static IBackgroundTaskRegistration RegisterBgTask(string bgTaskName)  
  38.         {  
  39.             try  
  40.             {  
  41.                 if (!IsAppHasPermission().Result) return null;  
  42.                 var bgRegister = IsBackgroundRegister(bgTaskName);  
  43.                 if (bgRegister != nullreturn bgRegister;  
  44.   
  45.                 var objBg = new BackgroundTaskBuilder()  
  46.                 {  
  47.                     Name = bgTaskName 
  48.                     
  49.                 };  
  50.   
  51.                 objBg.SetTrigger(_setTrigger);  
  52.                  
  53.                 bgRegister = objBg.Register();  
  54.                 return bgRegister;  
  55.             }  
  56.             catch (Exception exception)  
  57.             {  
  58.   
  59.             }  
  60.             return null;  
  61.         }  
  62.   
  63.         private static IBackgroundTaskRegistration IsBackgroundRegister(string bgTaskName)  
  64.         {  
  65.             var bgTask = BackgroundTaskRegistration.AllTasks.Where(taskReg => taskReg.Value.Name == bgTaskName)  
  66.                     .Select(bgTask1 => bgTask1.Value).FirstOrDefault();  
  67.             return bgTask;  
  68.         }  
  69.   
  70.           
  71.     }  
I hope, you understood how to implement ToastContextMenuItem concept.