WindowsPhone 8.1: Action Center Integration Sample, Beginners Level (C# and XAML )

Introduction

A highly requested Notification Center feature is now available in WindowsPhone 8.1. Action Center will allow you to quickly access the settings pages like Airplane mode, Wi-Fi Settings, Bluetooth settings and so on. This will also report about alerts, non-toast notifications, update histories and so on. Action Center is available via a swipe down from the top of your device, even from the lock screen. However I am proud to say this is the longest article in my blog :).

Fortunately a developer can access the "Action Center" like the following variety of ways.

  • Sending a local toast notification to the Action Center with a popup.

  • Sending a toast notification directly to Action Center, without showing a popup.

  • Remove a notification from the Action Center.

  • Update a notification from the Action Center.
Requirements
  • Make sure you've downloaded and installed the Windows Phone 8.1 SDK. For more information, see Get the SDK.

  • I assume you're going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you need to use some additional steps. For more info, see Register your Windows Phone device for development.

  • This article assumes you're using Microsoft Visual Studio Express 2013 for Windows.

Description

Previously in WindowsPhone 8.0, there was no Action Center in the phone. One of the biggest changes in Windows Phone 8.1 was the introduction of the Windows Phone Action Center. So the Action Center will allow you to quickly access the settings pages like Airplane mode, Wi-Fi Settings, Bluetooth settings and so on. Ok, it's time to start development with the following procedure.

Step 1

  1. Open Microsoft Visual Studio Express 2013 for Windows.

  2. Create a new project using the "Blank App" template available under Visual C# -> Store Apps -> Windows Phone Apps. (For example project name: ActionCenterSample.)

    new project
Step 2

Add the following XAML code to the MainPage.xaml page and run the app.
  1. <Grid Background="White">    
  2.        <ScrollViewer ZoomMode="Enabled">    
  3.        <StackPanel Margin="5" Orientation="Vertical">    
  4.            <!--Title of tutorial-->    
  5.            <TextBlock Margin="5" TextLineBounds="Full" FontSize="28" Text="WP8.1 ActionCenter Tutorials" Foreground="#FF1BC982" />    
  6.            <Rectangle Fill="Blue" Height="0.5"/>    
  7.                
  8.            <!--Iteracting with Action Center-->    
  9.            <Button Name="BtnSendToast" HorizontalAlignment="Stretch" Content="Send notification with toast popup" Background="#FF3FD483" Click="BtnSendToast_Click"/>    
  10.            <Button Name="BtnSendToastNoPopup" HorizontalAlignment="Stretch" Content="Send notification without toast popup" Background="#FF3FD483" Click="BtnSendToastNoPopup_Click"/>    
  11.            <Button Name="BtnRemoveToast" HorizontalAlignment="Stretch" Content="Remove notifications from app" Background="#FF3FD483"/>    
  12.            <Button Name="BtnUpdateToast" HorizontalAlignment="Stretch" Content="Update notifications from app" Background="#FF3FD483" Click="BtnUpdateToast_Click"/>    
  13.                
  14.            <!--About ActionCenter-->    
  15.            <TextBox VerticalAlignment="Bottom" Header="About ActionCenter:" TextWrapping="Wrap" BorderBrush="#FF23E0D8" Foreground="#FF736B74" IsHitTestVisible="False" IsColorFontEnabled="true">    
  16.                <TextBox.HeaderTemplate>    
  17.                    <DataTemplate>    
  18.                        <TextBlock Text="{Binding}" FontSize="23" Foreground="#FFD318E6"/>    
  19.                    </DataTemplate>    
  20.                </TextBox.HeaderTemplate>    
  21.                <TextBox.Text >    
  22.                    A highly requested Notification Center feature included in Windows Phone 8.1,Action Center will allow you to quickly access the settings pages like Airplane mode, Wi-Fi Settings, Bluetooth settings etc.    
  23.                    from a native app. This will also report you about alerts, non-toast notifications, update histories etc.Action Center is available via a swipe down from the top of your device, even from the lock screen.    
  24.                </TextBox.Text>    
  25.            </TextBox>    
  26.        </StackPanel>    
  27.        </ScrollViewer>    
  28.    </Grid>    
When we run the preceding XAML code, your screen will be shown as:

code output

Note: To interact with the Windows Phone Notification Center, the developer must be set the Toast Capable option to "Yes" from the "Application Tab" of the Package.appxmanifest file.

application

Otherwise when you click on the send notification button from the MainPage, you will get a warning like this.

MainPage

Step 3

Before starting to send notifications from the app we need to check the following phone NotificationSettings using the "ToastNotificationManager" class.
  1.  public bool CanSendToasts()   
  2.  {   
  3.     bool canSend = true;   
  4.     var NotifierStatus = ToastNotificationManager.CreateToastNotifier();   
  5.     //Check Notification settings status   
  6.     if (NotifierStatus.Setting != NotificationSetting.Enabled)   
  7.     {   
  8.        string ReasonMessage = "unknown error";   
  9.        switch (NotifierStatus.Setting)   
  10.        {   
  11.           case NotificationSetting.DisabledByGroupPolicy:   
  12.           ReasonMessage = "An administrator has disabled all notifications on this computer through group policy. The group policy setting overrides the user's setting.";   
  13.           break;   
  14.           case NotificationSetting.DisabledByManifest:   
  15.           ReasonMessage = "To send a toast from app,developer must be set Toast Capable option to 'Yes' from 'Application Tab' of Package.appxmanifest file.";   
  16.           break;   
  17.           case NotificationSetting.DisabledForApplication:   
  18.           ReasonMessage = "The user has disabled notifications for this app.";   
  19.           break;   
  20.           case NotificationSetting.DisabledForUser:   
  21.           ReasonMessage = "The user or administrator has disabled all notifications for this user on this computer.";   
  22.           break;   
  23.        }   
  24.        string errroMessage = String.Format("Can't send a toast.\n{0}", ReasonMessage);   
  25.        DisplayMessage(errroMessage);   
  26.        canSend = false;   
  27.     }   
  28.     return canSend;   
  29.  }   
I hope you already know, from the 8.1 OS version in phone settings there is an option for turning off /on notifications from a specific app or all apps. So in this case we can't send a toast and need to check the notification settings to display a related error message. See in the code above I wrote a method called CanSendToasts(), if it returns "true" then it means you can send a toast, otherwise you can't send a toast from the app.

Step 4

Let's assume we pass all the "NotificationSettings". And now we are ready to send local toast notifications to the Action Center. For simplicity I made a common method to send local toast notifications. So the helper method name is MakingToastNotification() that is having parameters (ToastTitle ,ToastBody ,Tag,Group, IsToastPopUpRequired).
  1.  public void MakingToastNotification(string ToastTitle, string ToastBody, string strTag, string strGroup, bool IsToastPopUpRequired)   
  2.  {   
  3.     // Using the ToastText02 toast template. This template contains a maximum of two text elements. The first text element is treated as    a header text and is always bold.   
  4.     ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;   
  5.    
  6.     // Retrieve the content part of the toast so we can change the text.   
  7.     XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);   
  8.    
  9.     //Find the text component of the content   
  10.     XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");   
  11.    
  12.     // Set the text on the toast.   
  13.     // The first line of text in the ToastText02 template is treated as header text, and will be bold.   
  14.        toastTextElements[0].AppendChild(toastXml.CreateTextNode(ToastTitle));//Toast notification title   
  15.     toastTextElements[1].AppendChild(toastXml.CreateTextNode(ToastBody + " (Tag:" + strTag + ", Group:" + strGroup + ")"));//Toast notificat   ion body   
  16.    
  17.     // Set the duration on the toast   
  18.     IXmlNode toastNode = toastXml.SelectSingleNode("/toast");   
  19.     ((XmlElement)toastNode).SetAttribute("duration""long");   
  20.     ToastNotification toast = new ToastNotification(toastXml);   
  21.     toast.ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(10);   
  22.    
  23.     //Check Toast popup required to display   
  24.     if(!IsToastPopUpRequired)   
  25.     {   
  26.        toast.SuppressPopup = true;//to send notification directly to action center without displaying a popup on phone.   
  27.     }   
  28.    
  29.     //Note: Tag & Group properties are optional,but these are userful for delete/update particular notification from app   
  30.     toast.Tag = strTag;   
  31.     toast.Group = strGroup;   
  32.    
  33.     ToastNotificationManager.CreateToastNotifier().Show(toast);   
  34.  }   
Note: See the highlighted color in the code above. When we want to send a local toast notification directly to the Action Center without showing a toast popup, we need to set "toast.SuppressPopup = true;".

Step 5

Now we have made all the necessary methods for interacting with the notification center. OK let's play with the following Action Center interactions from the app.
  1. Sending a local notification to the Action Center

    Initially the Action Center will show you the "no notifications" message.

    no notification

    In the following code I am trying to send a local toast notification to the Action Center with a toast popup, so I set the fifth parameter of the helper method (IsToastPopUpRequired) to "true".
    1. //Sending local toast notifications to action scenter with popup .   
    2.  int ToastCount = 0;   
    3.  private void BtnSendToast_Click(object sender, RoutedEventArgs e)   
    4.  {   
    5.     //Check notificationsettings status from user device   
    6.     if (CanSendToasts())   
    7.     {   
    8.        MakingToastNotification("Toast_with_Popup: ""Notitification " + ToastCount++, "T" + ToastCount.ToString(), "G1"true);   
    9.     }   
    10.  }   
    action center

    After sending some local notifications, our app notifications will be shown in the Action Center like this:

    action center sample

  2. Sending a local notification to the Action Center without toast popup

    In the following code I am trying to send local toast notification to the Action Center without showing a toast popup, so I set the fifth parameter of the helper method (IsToastPopUpRequired) to "false".
    1. //Sending local toast notifications to action scenter without popup .   
    2.  private void BtnSendToastNoPopup_Click(object sender, RoutedEventArgs e)   
    3.  {   
    4.     //Check notification settings status from user device   
    5.     if (CanSendToasts())   
    6.     {   
    7.        MakingToastNotification("Toast_without_Popup: ""Notitification " + ToastCount++, "T"+ToastCount.ToString(), "G2"false);   
    8.     }   
    9.  }   
  3. Remove specific notification from the Action Center

    We can remove a specific notification based on its Tag and Group property values. Here I am trying to remove the notification that has the Tag property value of "T1", however I am also showing other ways for removing notification in comment lines.
    1. //Remove notifications from code .   
    2. private void BtnRemoveToast_Click(object sender, RoutedEventArgs e)   
    3. {   
    4.    //To Remove all notifications with the given Tag id   
    5.    ToastNotificationManager.History.Remove("T1");   
    6.   
    7.    //To Remove all notifications with the given Tag id and Group id   
    8.    //ToastNotificationManager.History.RemoveGroup("T1","G1");   
    9.   
    10.     //To Remove all notifications with the given Group id   
    11.    // ToastNotificationManager.History.RemoveGroup("G1");   
    12.   
    13.     //To Remove all notifications   
    14.  //ToastNotificationManager.History.Clear();   
    15.      
    16.     DisplayMessage("Notifications with Tag 'T1' have been removed.\n Open action center to verify.");   
    17.  }   
  4. Update specific notification from the Action Center

    We can update a specific notification based on its Tag and Group property values. Here, I am trying to update the notification with the Tag property value of "T1" and Group property value of "G1".
    1. //Update notifications from code .   
    2. private void BtnUpdateToast_Click(object sender, RoutedEventArgs e)   
    3. {   
    4.    MakingToastNotification("Toast_without_Popup: ""Notitification 1 is updated ","T1""G1"false);//Update the notification whi   ch is having Tag T1 ,Group G1   
    5.    DisplayMessage("Notifications has been updated with new content.");   
    6. }  
Summary

From this article we have learned "Integrate Notification Center in WindowsPhone 8.1 application". I hope I wrote this article with my best level. When writing this article, I spent a lot of hard work to make a nice presentation to understand the article at the beginners level.
 
This article is also available at my original blog.