La semana pasada publicamos Cell·SDK 1.2 con un montón de nuevas características y algunas correcciones que hacen del desarrollo multiplataforma en iOS, Android y Windows Phone aún más sencillo.
En el post de hoy vamos a ver cómo enlazar lo que tenemos en el tutorial de Push notifications para Windows Phone y lo que podemos encontrar en la web de Microsoft sobre cómo mandar notificaciones a nuestros dispositivos.
Con el mismo código fuente que tenemos disponible en Github para la aplicación de ejemplo en el dispositivo nos va a valer para este ejemplo.
Tenemos que tener en cuenta que debemos programarnos una pequeña aplicación/servicio para poder enviar notificaciones al servicio de notificaciones de Microsoft. Tal y como vemos en el diagrama y documentación de Microsoft:
Nosotros tenemos que implementarnos el “Cloud Service” así que vamos a ver un ejemplo de cómo hacerlo según se indica aquí. De este último enlace sólo nos interesa la parte de “Sending a Toast Notification”
Vamos a crear un proyecto de ASP.NET vacío y vamos a incluir cuatro controles TextBox y un botón para enviar la notifiación:
Ahora vamos a darle código al evento clic del botón:
protected void SendToast_Click(object sender, EventArgs e) { try { // Get the URI that the Microsoft Push Notification Service returns to the push client when creating a notification channel. // Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send // notifications out to. string subscriptionUri = TextBoxUri.Text.ToString(); HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri); // Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service. // HTTP POST is the only method allowed to send the notification. sendNotificationRequest.Method = "POST"; // The optional custom header X-MessageID uniquely identifies a notification message. // If it is present, the same value is returned in the notification response. It must be a string that contains a UUID. // sendNotificationRequest.Headers.Add("X-MessageID", ""); // Create the toast message. string toastMessage = "<?xml version="1.0" encoding="utf-8"?>" + "" + "" + "" + TextBoxTitle.Text.ToString() + "" + "" + TextBoxSubTitle.Text.ToString() + "" + " " + ""; // 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. HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse(); string notificationStatus = response.Headers["X-NotificationStatus"]; string notificationChannelStatus = response.Headers["X-SubscriptionStatus"]; string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"]; // Display the response from the Microsoft Push Notification Service. // Normally, error handling code would be here. In the real world, because data connections are not always available, // notifications may need to be throttled back if the device cannot be reached. TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus; } catch (Exception ex) { TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString(); }
Este código puede estar tanto en una aplicación web, una aplicación de Windows forms, un servicio de Azure, etc…
Tan sólo tenéis que montarlo, desplegar la aplicación de ejemplo de github en el dispositivo ó en el emulador y copiar el Channel ID que saldrá en la ventana de Output de Visual Studio:
Este código lo introducimos en la página web que hemos creado en el textbox primero y recibiremos en el dispositivo o emulador una notifiación Toast:
Hay tres tipos de notificaciones para Windows Phone que podemos enviar:
- Toast: Con documentación y ejemplos aquí
- Tile: Con documentación y ejemplos aquí.
- Raw: Con documentación y ejemplos aquí.
Os recomiendo que probéis a enviar otro tipo de notificaciones, en este ejemplo hemos usado el ejemplo de envío de notificaciones Toast.
Para ver el código fuente de la aplicación y cómo es la API Unificada para Android, iOS y Windows Phone de Cell·SDK no tenéis más que pasaros por aquí
Espero que os sirva.
Juan María Laó Ramos.