Google WindowsPhone 8.1: Action Center Sample,Beginners level (C#-Xaml). | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Thursday 4 December 2014

WindowsPhone 8.1: Action Center Sample,Beginners level (C#-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 etc. 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.This is probably one of the longest article in my blog :) .

Fortunately a developer can access 'Action Center' like following variety of ways. 
  • Sending a local toast notification to action center with 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 assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see Register your Windows Phone device for development.
  • This post assumes you’re using Microsoft Visual Studio Express 2013 for Windows.

Description:

Previously in windowsphone 8.0,there was no action center on phone.One of the biggest changes in Windows Phone 8.1 was the introduction of the Windows Phone Action Center. So Action Center will allow you to quickly access the settings pages like Airplane mode, Wi-Fi Settings, Bluetooth settings etc.Ok its time to start development with following steps.
Step 1:
1)Open Microsoft Visual Studio Express 2013 for Windows.
2)Create new project using the "Blank App" template available under Visual C# -> Store Apps -> Windows Phone Apps. (for example project name :ActionCenterSample)
Step 2:
Add following xaml code in 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 run the above xaml code,your screen will be appeared as
Note: To interact with the Windows Phone Notification Center, developer must be set Toast Capable option to 'Yes' from 'Application Tab' of Package.appxmanifest file.

Otherwise when you click on send notification button from MainPage, you will be warning like this 

Step 3:
Before start to send notifications from app.we need to check following phone NotificationSettings with help of '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 8.1 OS version in phone settings there is an option for turn off /on notifications from a specific app /all apps.So in this case we can't send toast and need to check the notification settings to displaying related error message.See in above code i wrote a method called CanSendToasts(),if it is return 'true' then it means you can able to send toast,otherwise you can't send toast from app.

Step 4:
Lets assume we pass all 'NotificationSettings'.And now we are ready to send local toast notifications to action center.For simplicity i made a common method to send local toast notifications .So helper method name is MakingToastNotification() which is having parameters (ToastTitle ,ToastBody ,Tag,Group,IsToastPopUpRequired). You’ll need to manipulate the XML document to set the different tile properties, like in the following example.

  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 notification 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 above code,When we want to send a local toast notification directly to action center without showing toast popup, we need to set "toast.SuppressPopup = true;" 

Step 5:
Now we made all neccessary  methods for interacting with notification center. OK let's play with following action center interactions from app.
1)Sending a local notification to action center
Initially action center will shows you with 'no notifications' message.
In below code i am trying send local toast notification to action center with toast popup,so i set fifth parameter of helper method (i.e IsToastPopUpRequired) is '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.         }  
After sending some local notifications , our app notifications will be shown in action center like this
2)Sending a local notification to action center without toast popup:
In below code i am trying send local toast notification to action center without showing toast popup,so i set fifth parameter of helper method (i.e IsToastPopUpRequired) is '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 & Group property values . Here i am trying to remove notification which is having Tag property value is 'T1' ,However i am also explained different 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 & Group property values . Here i am trying to update notification which is having Tag property value is 'T1' and Group property value is '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 notifcation which is having Tag T1 ,Group G1  
  5.             DisplayMessage("Notifications has been updated with new content.");  
  6.         }  

ActionCenterSample
Summary:
From this article we have learned "Integrate Notification Center in windowsphone 8.1 application".Hope i wrote this post with my best level,When writing this article, i had taken lot of hard works and making nice presentation to understand the article at beginners level.


FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

No comments:

Post a Comment

Search Engine Submission - AddMe