מדריך Windows Phone

מדריך Windows Phone – שימוש ב Push Notifications

‏ • Sela

מערכת ההפעלה Windows Phone מספקת מנגנון אשר מאפשר לשרת חיצוני לשלוח הודעות מיוחדות לפלאפון שהאפליקציה שלנו תוכל להגיב להם. בפרק זה נראה כיצד ניתן להשתמש במנגנון הזה הנקרא Push Notifications.

איך זה עובד?

ראשית האפליקציה שלנו על הפלאפון נרשמת באמצעות API מיוחד בשרתים של מיקרוסופט (שלבים 1 ו 2 בתרשים הבא). השרת של מיקרוסופט מחזיר תוצאה בצורת כתובת URI מסוימת שמייצגת כעת את מכשיר הפלאפון שלנו והאפליקציה שלנו (שלב 3). את הכתובת URI שקיבלנו אנו נשלח לשרת שלנו (שלב 4). כעת כאשר השרת שלנו יחליט שהוא רוצה לשלוח לנו הודעה, הוא יפנה לשרתים של מיקרוסופט ויציין את כתובת ה URI שהעברנו לו, בצירוף פרטי ההודעה (שלב 5). השרת של מיקרוסופט ישלח לנו את ההודעה המבוקשת (שלב 6).

 

מדריך Windows Phone – שימוש ב Push Notifications

 

 

סוגי הודעות

ישנם 3 סוגי הודעות שניתן לשלוח באמצעות מנגנון Push Notifications:

  • הודעת Toast – להודעה זו מבנה מוגדר היטב (תוך שימוש ב XML) והוא מכיל כותרת (Title), תוכן (Content) ופרמטר נוסף (Paramater). כאשר הודעת Toast מגיעה לפלאפון, מערכת ההפעלה מציגה את ההודעה (כותרת ותוכן) בתקרת המסך, כאשר לחיצה על ההודעה תפתח את האפליקציה שלנו, בצירוף הפרמטר שהגיע בהודעה. להלן דוגמא לאופן שבו מוצגת הודעת Toast:

מדריך Windows Phone – שימוש ב Push Notifications

 

  • הודעת Tile – הודעה זו גורמת לעדכון של ה Tile של האפליקציה, מבנה ההודעה מכיל את כל מה שניתן לשנות ב Tile , כותרת, מספר, תמונת רקע, ועוד. להסבר מורחב על Tile ראה את הפרק בנושא.
  • הודעת Raw – בהודעה מסוג Raw ניתן לשלוח כל מידע שנרצה, באיזה פורמט שנרצה והמידע יועבר לתוך האפליקציה, אבל רק אם האפליקציה פעילה.

 

 

דוגמא לשימוש ב Push Notifications

כעת נראה דוגמא כיצד ליצור שירות שמאפשר שליחת הודעות דרך מנגנון Push Notifications, וכן כיצד נרשמים לקבלת הודעות כאלו באפליקציה שלנו.

בשלב ראשון ניצור שירות WCF משלנו שיתארח בשרת IIS המקומי (לשם דיבוג נוח) שישלח הודעות באמצעות שירות MPNS של מיקרוסופט (Microsoft Push Notification Service). לאחר מכן ניצור אפליקציית Windows Phone שתירשם לקבלת הודעות בשרת של מיקרוסופט.

 

יצירת צד השרת

נפתח פרויקט חדש מסוג WCF Service Application ונגדיר שירות בעל המבנה הבא:

[ServiceContract()]
public interface INotificationService
{
  [OperationContract]
  void SendToast(Uri uri, string title, string content);

  [OperationContract]
  void SendTile(Uri uri, string tokenID, string backImageUri, int count, string title,
                        string backBackImageUri, string backTitle, string backContent);

  [OperationContract]
  void SendRAW(Uri uri, string value1, string value2);
}

 

לשירות שלנו יש 3 פונקציות, כאשר כל פונקציה מבצעת שליחה של הודעה מסוג אחר.

כעת נממש את הפונקציות הנ"ל כך שכל אחת תשלח הודעה מהסוג המתאים.

public void SendToast(Uri uri, string title, string content)
{
  var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(uri);

  // Create an HTTPWebRequest that posts the toast notification to MPNS
  sendNotificationRequest.Method = "POST";

  // Create the toast message.
  string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<wp:Notification >"<wp:Toast>" +
          "<wp:Text1>" + title + "</wp:Text1>" +
          "<wp:Text2>" + content + "</wp:Text2>" +
          "<wp:Param>/Page2.xaml?NavigatedFrom=Toast Notification</wp:Param>" +
      "</wp:Toast> " +
  "</wp:Notification>";

  // Set the notification payload to send.
  byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);

  // Set the web request content length.
  sendNotificationRequest.ContentLength = notificationMessage.Length;
  sendNotificationRequest.ContentType = "text/xml";
  sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
  sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

  using (Stream requestStream = sendNotificationRequest.GetRequestStream())
  {
    requestStream.Write(notificationMessage, 0, notificationMessage.Length);
  }

  // Send the notification and get the response.
  var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
}

public void SendTile(Uri uri, string tokenID, string backImageUri, int count, string title,
                      string backBackImageUri, string backTitle, string backContent)
{
  var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(uri);

  // Create an HTTPWebRequest that posts the Tile notification to MPNS
  sendNotificationRequest.Method = "POST";

  // Create the Tile message.
  string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<wp:Notification >"<wp:Tile>" +
        "<wp:BackgroundImage>" + backImageUri + "</wp:BackgroundImage>" +
        "<wp:Count>" + count + "</wp:Count>" +
        "<wp:Title>" + title + "</wp:Title>" +
        "<wp:BackBackgroundImage>" + backBackImageUri + "</wp:BackBackgroundImage>" +
        "<wp:BackTitle>" + backTitle + "</wp:BackTitle>" +
        "<wp:BackContent>" + backContent + "</wp:BackContent>" +
      "</wp:Tile> " +
  "</wp:Notification>";

  // Set the notification payload to send.
  byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);

  // Set the web request content length.
  sendNotificationRequest.ContentLength = notificationMessage.Length;
  sendNotificationRequest.ContentType = "text/xml";
  sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
  sendNotificationRequest.Headers.Add("X-NotificationClass", "1");

  using (Stream requestStream = sendNotificationRequest.GetRequestStream())
  {
    requestStream.Write(notificationMessage, 0, notificationMessage.Length);
  }

  // Send the notification and get the response.
  var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
}

public void SendRAW(Uri uri, string value1, string value2)
{
  var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(uri);

  // Create an HTTPWebRequest that posts the raw notification to MPNS
  sendNotificationRequest.Method = "POST";

  // Create the raw message.
  string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<root>" +
      "<Value1>" + value1 + "<Value1>" +
      "<Value2>" + value2 + "<Value2>" +
  "</root>";

  // Set the notification payload to send.
  byte[] notificationMessage = Encoding.Default.GetBytes(rawMessage);

  // Set the web request content length.
  sendNotificationRequest.ContentLength = notificationMessage.Length;
  sendNotificationRequest.ContentType = "text/xml";
  sendNotificationRequest.Headers.Add("X-NotificationClass", "3");

  using (Stream requestStream = sendNotificationRequest.GetRequestStream())
  {
    requestStream.Write(notificationMessage, 0, notificationMessage.Length);
  }

  // Send the notification and get the response.
  var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
}

 

יצירת אפליקציית Windows Phone

כעת שיש לנו שירות שיודע לשלוח הודעות כנ"ל, נבנה אפליקציה ל Windows Phone שנרשמת בשירות Push Notifications של מיקרוסופט ומקבלת URI שבעזרתו ניתן לשלוח הודעות.

ניצור אפליקצית Windows Phone ונגדיר שני כפתורים. הכפתור הראשון, כפתור Register יבצע את הרישום בשרתים של מיקרוסופט. הכפתור השני, כפתור Send Toast, יגרום (בעקיפין) לשליחת הודעת Toast.

כמובן שבאפליקציה בעולם האמתי אנו נעביר את ה URI שקיבלנו מהשרת של מיקרוסופט לשרת שלנו והוא ישלח הודעות מתי שהוא ימצא לנכון, ולא בעקבות בקשה מפורשת מצד האפליקציה שלנו.

להלן המימוש של שני הכפתורים:

private string channelName = "testToast";
private HttpNotificationChannel httpChannel;

private void Register_Button_Click(object sender, RoutedEventArgs e)
{
  httpChannel = HttpNotificationChannel.Find(channelName);

  if (httpChannel == null)
  {
    //Create the channel
    httpChannel = new HttpNotificationChannel(channelName);
    httpChannel.Open();
    httpChannel.BindToShellToast();
  }
}

private void Send_Button_Click(object sender, RoutedEventArgs e)
{
  var client = new NotificationServiceClient();
  client.SendToastAsync(httpChannel.ChannelUri, "hello", "push notifications");
}

 

והתוצאה המתקבלת:

 

מדריך Windows Phone – שימוש ב Push Notifications

 

שימו לב שהודעת Toast מוצגת רק כאשר האפליקציה לא נמצאת כרגע בשימוש. במידה והאפליקציה פעילה ניתן להירשם לאירוע מתאים ולקבל את המידע שהגיע בהודעת ה Toast ישירות.

באופן דומה ניתן לשלוח גם הודעות Tile ו Raw, שכן צד השרת כבר ממומש לנו.

תגיות: , , , ,

arikp

אריק פוזננסקי הוא יועץ בכיר ומרצה בסלע. הוא השלים שני תארי B.Sc. במתמטיקה ומדעי המחשב בהצטיינות יתרה בטכניון. לאריק ידע נרחב בטכנולוגיות מיקרוסופט, כולל .NET עם C#, WPF, Silverlight, WinForms, Interop, COM/ATL, C++ Win32 ו reverse engineering.

תגובות בפייסבוק