|
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:
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.
After application registered and ready to receive notifications from WNS, let’s overview how the whole process works:
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();
}
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:
Note: WinRT provides multiple tile and toasts templates. Please refer to documentation for full templates list.
Badges:
Note: Windows 8 enables developer to provide two tiles sizes. Please refer to documentation for full templates list.
Toast:
Badge notification can be either number or one of pre-defined glyphs:
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;
}
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 “NotificationsExtensions” which greatly simplifies this work. My sample uses this library and all the “ContentFactory” 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/
|
|