设为首页 收藏本站
查看: 1196|回复: 0

win8 app – Live tiles, toasts, badges and Push Notifications

[复制链接]

尚未签到

发表于 2015-5-21 11:04:34 | 显示全部楼层 |阅读模式
  http://software.intel.com/zh-cn/articles/Wenxi/
  Windows 8 provides interesting way to “interact” with user even when application is not active anymore.

Push Notifications
  Windows Push Notifications (WNS) in Windows 8 is quite similar to the Windows Phone 7 Push Notification (MPNS) model. It uses cloud-based push notification services to deliver notifications to registered clients.
  To enable application receiving push notifications developer must register it at Windows Push Notifications & Live Connect site. The process is very simple – developer provides Package display name and publisher found in application manifest:
DSC0000.png
  and site provides with updated package name (looks like BUILD.XXXXXXXX-XXXX-XXXX-XXXX), client secret code and package security identifier (SID, looks like ms-app://s-1-15-2-3589536595-1843142753-3412205061-910709869-3859942861-2189978342-XXXXXXXXX ). Developer must modify package name in application manifest. Created applications can be managed Live App management site and retrieve information about any registered application, usage, caps, etc.
DSC0001.png
  After application registered and ready to receive notifications from WNS, let’s overview how the whole process works:
DSC0002.png
  
  1. Metro style application uses WinRT APIs (Notification Client Platform on diagram) to open new channel to server (or reconnect with previously created channel). At the end of the process, application receives unique URI which will be used in next step.
  2. Any 3rd party application (Metro, classic, WPF, cloud-based service), which has URI obtained in previous step + client secret/SID combination can request Authorization token from WNS and then POST message to provided URI using received authorization token.
  3. 3rd party application (in my simplest case – console app) requests authorization token using client secret and SID, prepares XML payload (the message which WNS sends to client) and sends POST message to URI (from 1st step)
  4. WNS verifies provided information, alters Windows 8 client machine and delivers the message payload to client notification platform. Client notification platform responsible on updating tile/badge, showing toast notification, updating lock screen (if application has lock screen access) and deliver notifications to Metro app if still active.
  Now let’s see the application described in step 2. It has 2 main functions – GetAccessToken and Push:




        private static string GetAccessToken()
        {
            string url = "https://login.live.com/accesstoken.srf";
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string sid = HttpUtility.UrlEncode("ms-app://s-1-15-2-3589536595-1843142753-3412205061-910709869-3859942861-2189978342-XXXXXXXXX");
            string secret = HttpUtility.UrlEncode("nGr4eaiyh1mlk2wD8-o51a21aS7s04De");
            string content = "grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com";
            string data = string.Format(content, sid, secret);
            byte[] notificationMessage = Encoding.Default.GetBytes(data);
            request.ContentLength = notificationMessage.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(notificationMessage, 0, notificationMessage.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            string result;
            using (Stream responseStream = response.GetResponseStream())
            {
                var streamReader = new StreamReader(responseStream);
                result = streamReader.ReadToEnd();
            }
            return result;  
        }  




        private static HttpStatusCode Push(string pushUri, string accessToken, string type, string notificationData)
        {
            var subscriptionUri = new Uri(pushUri);
            var request = (HttpWebRequest)WebRequest.Create(subscriptionUri);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Headers = new WebHeaderCollection();
            request.Headers.Add("X-WNS-Type", type);
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            byte[] notificationMessage = Encoding.Default.GetBytes(notificationData);
            request.ContentLength = notificationMessage.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(notificationMessage, 0, notificationMessage.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode;
        }  
  The functions are pretty simple – first returns stream with Authorization token, second uses URI obtained in step 1 (see diagram) + authorization token + notification type (set as custom header, X-WNS-Type) and sends notification payload using HTTP PUSH method.
  The main function:




  static void Main(string[] args)
        {
            var jsreader = new JsonTextReader(new StringReader(GetAccessToken()));
            var json = (JObject)new JsonSerializer().Deserialize(jsreader);
            string accessToken = json["access_token"].ToString();
            string pushUri = "https://sin.notify.windows.com/?token=AgUAAACIKQpzu%2baM1pW1h0P6lO1wdjor994WC%2bH8UAmHqdaxKsLMsufXFrhgsgksPH3SLyf4RJvSwaYkGzRW0FJtpKXMyneKR3yBM7kcAx%2b7eSun2pIPA8uClS86ixYlxOcoD5Y%3d";
            HttpStatusCode status;
            //Send Badge notification
            string badgeNotification = "";
            status = Push(pushUri, accessToken, "wns/badge", badgeNotification);
            Console.WriteLine("Badge notification send reault: " + status.ToString());
            //Send Toast notification
            string tostNotification = "" +
                                      "" +
                                          "" +
                                              "" +
                                                  "" +
                                                  "Love is in the air (PUSHED)!" +
                                                  "Someone sends you love waves!" +
                                              "" +
                                          "" +
                                      "";
            status = Push(pushUri, accessToken, "wns/toast", tostNotification);
            Console.WriteLine("Toast notification send reault: " + status.ToString());
            //Send Tile notification
            string tileNotification = "" +
                                      "" +
                                          "" +
                                              "" +
                                                  "" +
                                                  "Someone loves you from the distance!" +
                                              "" +
                                          "" +
                                      "";
            status = Push(pushUri, accessToken, "wns/tile", tileNotification);
            Console.WriteLine("Tile notification send reault: " + status.ToString());
            Console.WriteLine("Press ENTER to exit...");
         
            Console.ReadLine();
        }  
DSC0003.png
  Also this code is pretty simple it has some important information – the notification payload XML formats. In case of Toast and Tile notification this format actually dictates which information and how it will be presented to user. To learn more about Toast/Tile formats please refer to documentation.
  Now when external parts are ready, let’s write Metro app functionality.

Updating tiles/toasts/badges
  Tile:
DSC0004.png
  
  Note: WinRT provides multiple tile and toasts templates. Please refer to documentation for full templates list.
  Badges:
  
DSC0005.png
  
  Note: Windows 8 enables developer to provide two tiles sizes. Please refer to documentation for full templates list.
  Toast:
  
DSC0006.png
  
  Badge notification can be either number or one of pre-defined glyphs:
DSC0007.png
  
  Note: The location of badge is predefined.
  Let’s get started with updating those items. First I will show how to open push notification channel and obtain URI:
  




        async private Task SetupPushNotifications()
        {
            var pushNotificationChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
            var channelUri = pushNotificationChannel.Uri;
            System.Diagnostics.Debug.WriteLine(channelUri); //This URI will be used in application described above
            //Optional for my sample - not really used
            //pushNotificationChannel.PushNotificationReceived += pushNotificationChannel_PushNotificationReceived;
        }
        private void pushNotificationChannel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
        {
            switch (args.NotificationType)
            {
                case PushNotificationType.Badge:
                    //Not used in sample, but usefull to process incoming badge notification messages
                    //notificationContent = args.BadgeNotification.Content.GetXml();
                    //...
                    break;
                case PushNotificationType.Tile:
                    //Not used in sample, but usefull to process incoming tile notification messages
                    //notificationContent = args.TileNotification.Content.GetXml();
                    //...
                    break;
                case PushNotificationType.Toast:
                    //Not used in sample, but usefull to process incoming toast notification messages
                    //notificationContent = args.ToastNotification.Content.GetXml();
                    //...

                    break;
            }
            // prevent the notification from being delivered to the UI
            args.Cancel = true;
        }  
DSC0008.png
  The code snippet creates push notification channel for main application tile and prints out received URI to debug console. I will be using this URI in app described above. Usually, application subscribes to received push notification messages using PushNotificationReceived event, but in my simple case I just provided the code snippet which is not really used.
  Note: If application uses secondary tiles (additional tiles created from within application code – will be covered later in this post), it must use CreatePushNotificationChannelForSecondaryTileAsync method of PushNotificationChannelManager to get unique URI for the tile. As described above, delivered notification will be processed by client push notification platform and presented on main screen.
  Now let’s see how to issue an update from within the application.
  Generally, updating all the of tiles/badges/toasts boils down to creating correct XML according to selected template, populating values and invoking Update method of desired UpdaterManager. Example of building such XML (in this case toast notification):
StringBuilder builder = new StringBuilder("");
builder.AppendFormat("");
            
builder.AppendFormat("{1}", TemplateName, SerializeProperties(Lang, BaseUri));
builder.Append("");
AppendAudioTag(builder);
            
builder.Append("");
return builder.ToString();//...
protected string SerializeProperties(string globalLang, string globalBaseUri)
{
    globalLang = (globalLang != null) ? globalLang : String.Empty;
    globalBaseUri = String.IsNullOrWhiteSpace(globalBaseUri) ? null : globalBaseUri;
    StringBuilder builder = new StringBuilder(String.Empty);
    for (int i = 0; i < m_Images.Length; i++)
    {
        if (!String.IsNullOrEmpty(m_Images.Src))
        {
            string escapedSrc = Util.HttpEncode(m_Images.Src);
            if (!String.IsNullOrWhiteSpace(m_Images.Alt))
            {
                string escapedAlt = Util.HttpEncode(m_Images.Alt);
                builder.AppendFormat("", i + 1, escapedSrc, escapedAlt);
            }
            else
            {
                builder.AppendFormat("", i + 1, escapedSrc);
            }
        }
    }
    for (int i = 0; i < m_TextFields.Length; i++)
    {
        if (!String.IsNullOrWhiteSpace(m_TextFields.Text))
        {
            string escapedValue = Util.HttpEncode(m_TextFields.Text);
            if (!String.IsNullOrWhiteSpace(m_TextFields.Lang) && !m_TextFields.Lang.Equals(globalLang))
            {
                string escapedLang = Util.HttpEncode(m_TextFields.Lang);
                builder.AppendFormat("{2}", i + 1, escapedLang, escapedValue);
            }
            else
            {
                builder.AppendFormat("{1}", i + 1, escapedValue);
            }
        }
    }
    return builder.ToString();
}
  To ease on routine work, updated version of Metro samples includes reusable library named &#8220;NotificationsExtensions&#8221; which greatly simplifies this work. My sample uses this library and all the &#8220;ContentFactory&#8221; classes in code below are defined there:
//Update badge
BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent();
if (badgeCount > 0)
    badgeContent.Number = badgeCount;
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification());
//Update application's main tile
ITileWideSmallImageAndText03 tileContent = TileContentFactory.CreateTileWideSmallImageAndText03();
tileContent.TextBodyWrap.Text = message;
tileContent.Image.Src = "ms-appx:///Images/" + image;
tileContent.RequireSquareContent = false;
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileContent.CreateNotification());
//Fire toast notification
IToastImageAndText02 templateContent = ToastContentFactory.CreateToastImageAndText02();
templateContent.TextHeading.Text = "Love is in the air!";
templateContent.TextBodyWrap.Text = message;
templateContent.Image.Src = "Images/Love.png";
templateContent.Image.Alt = "Placeholder image";
IToastNotificationContent toastContent = templateContent;
ToastNotification toast = toastContent.CreateNotification();
ToastNotificationManager.CreateToastNotifier().Show(toast);
  Once XXX_Content populated with data this code snippet uses relevant UpdateManager to update/show relevant item.

Secondary Tiles
  Updating secondary tiles:
Uri logo = new Uri("ms-appx:///images/Love.png");
Uri wideLogo = new Uri("ms-appx:///images/WideSecondary.png");
SecondaryTile secondaryTile = new SecondaryTile("LoveCatcher.SecondaryTile",
                                _isABoy.Value ? "A Boy" : "A Girl",
                                _isABoy.Value ? "Lonely Boy" : "Lonely Girl",
                                "pinnedID=" + (_isABoy.Value ? "BOY" : "GIRL"),
                                TileOptions.ShowNameOnWideLogo | TileOptions.ShowNameOnLogo,
                                logo,
                                wideLogo);
bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(GetElementRect(this));
txtStatus.Text = isPinned ? "Secondary tile successfully pinned." : "Secondary tile not pinned.";
  
  参考资料:http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2012/02/29/windows-8-consumer-preview-and-visual-studio-11-beta-live-tiles-toasts-badges-and-push-notifications-part-10-11.aspx
  http://www.jayway.com/2011/10/12/implementing-windows-8-push-notifications-an-example/
DSC0009.jpg

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-69161-1-1.html 上篇帖子: Win8.1 与 pl2303驱动 下篇帖子: 解决win8 下 eclipse 中文字体太小的问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表