Push Notification Service [WP7 learning note 13]

Source: Internet
Author: User
Tags response code

Why use the push notification service?

The Windows Phone execution model determines that only one third-party application can be run on the foreground, and the application can no longer run on the background, constantly pulling data to the cloud. Microsoft provides the push notification service to send update notifications to third-party applications. Because the server can actively initiate communications, it can effectively reduce the consumption of cell phone batteries.

For a complete authoritative description of push notifications for Windows Phone, see the msdn Document Description: http://msdn.microsoft.com/zh-cn/library/ff402537 (V = vs.92). aspx.

Content of this section

  • Windows Phone push notification Overview

  • Receive push notifications from Windows Phone

  • Send Windows Phone push notifications

  • Response code of the push notification service for Windows Phone

  • How to Set a callback for a Windows Phone registration request

  • Set verified web services to send push notifications for Windows Phone

  • How to send and receive Windows Phone toast notifications

  • How to send and receive tile notifications for Windows Phone

  • How to send and receive Windows Phone raw notifications

The MS process for pushing messages is described as follows:

Shows how client applications running on mobile phones push notification Uris from the push Client Service (1. Then, the push client service negotiates with the Microsoft push notification service (mpns) and returns a notification URI to the client application (2 and 3. Then, the client application sends this URI to cloud service (4 ). When a Web Service sends information to a client application, the Service uses this URI to send a push notification to the Microsoft push notification service (5, the Microsoft push notification service sends the push notification to an application running on a Windows Phone device (6.

Based on the push notification format and the load connected to the notification, the information is visually updated or toast notification is displayed as raw data sent to the application and application tile. After a push notification is sent, the Microsoft push notification service sends a response code to your web service, indicating that this notification has been received and will be sent to the device next time. However, the Microsoft push notification service does not provide end-to-end communication for sending push notifications from the Web service to devices.

The description of Jake Lin is:

Usage specification:

Windows Phone 7 currently only allows 15 third-party applications to use the push notification service;

Ask the user whether to use the push notification service;

This option allows you to cancel a subscription.

S message type:

Raw notification:

Data in any format can be sent;

Applications can process data as needed;

Application-related notification messages;

★It is sent only when the application is running.

Toast notification:

The sent data is in the specified XML format;

★If the application is running, the content is sent to the application;

★If the application is not running, the toast message box is displayed:

Two text descriptions are added to the app icon;

Interrupt the user's current operation, but it is temporary;

You can click to trace.

Tile notification:

The sent data is in the specified XML format;

★Will not be sent to the application;

★If you pin the application to start, the updated data will be sent to the tile of Start Screen:

It contains three attributes: Background, title, and counter;

Each attribute has a fixed format and position;

You can use the attributes, but not necessarily the three attributes.

Example Program (raw): mobile client code:

View code

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. net;
Using system. windows;
Using system. Windows. controls;
Using system. Windows. documents;
Using system. Windows. input;
Using system. Windows. Media;
Using system. Windows. Media. animation;
Using system. Windows. shapes;
Using Microsoft. Phone. controls;
Using Microsoft. Phone. notification;

Namespace push notification service
{
Public partial class mainpage: phoneapplicationpage
{
// Constructor
Public mainpage ()
{
Initializecomponent ();

// Holds the push channel that is created or found.
Httpicationicationchannel pushchannel;
// The name of our push channel.
String channelname = "rawsamplechannel ";
// Try to find the push Channel
Pushchannel = httpicationicationchannel. Find (channelname );
// If the channel was not found, then create a new connection to the PUSH Service.
If (pushchannel = NULL)
{
Pushchannel = new httpicationicationchannel (channelname );
// Register for all the events before attempting to open the channel.
Pushchannel. channeluriupdated + = new eventhandler <icationchannelurieventargs> (pushchannel_channeluriupdated );
Pushchannel. erroccurred + = new eventhandler <icationicationchannelerroreventargs> (pushchannel_erroccurred );
Pushchannel. httpnotificationreceived + = new eventhandler Pushchannel. open ();
}
Else
{
// The channel was already open, so just register for all the events.
Pushchannel. channeluriupdated + = new eventhandler <icationchannelurieventargs> (pushchannel_channeluriupdated );
Pushchannel. erroccurred + = new eventhandler <icationicationchannelerroreventargs> (pushchannel_erroccurred );
Pushchannel. httpnotificationreceived + = new eventhandler // Display the URI for testing purposes. Normally, the URI wocould be passed back to your web service at this point.
System. Diagnostics. Debug. writeline (pushchannel. channeluri. tostring ());
MessageBox. Show (string. Format ("channel URI is {0 }",
Pushchannel. channeluri. tostring ()));
}
}

Void pushchannel_httpnotificationreceived (Object sender, httpnotifeventeventargs E)
{
String message;

Using (system. Io. streamreader reader = new system. Io. streamreader (E. Notification. Body ))
{
Message = reader. readtoend ();
}

Dispatcher. begininvoke () =>
MessageBox. Show (string. Format ("received notification {0 }:\ n {1 }",
Datetime. Now. tow.timestring (), message ))
);
}

Void pushchannel_erroroccurred (Object sender, icationicationchannelerroreventargs E)
{
// Error handling logic for your particle application wocould be here.
Dispatcher. begininvoke () =>
MessageBox. Show (string. Format ("A push notification {0} error occurred. {1} ({2}) {3 }",
E. errortype, E. Message, E. errorcode, E. erroradditionaldata ))
);
}

Void pushchannel_channeluriupdated (Object sender, icationchannelurieventargs E)
{
Dispatcher. begininvoke () =>
{
// Display the new URI for testing purposes. Normally, the URI wocould be passed back to your web service at this point.
System. Diagnostics. Debug. writeline (E. channeluri. tostring ());
MessageBox. Show (string. Format ("channel URI is {0 }",
E. channeluri. tostring ()));
});
}
}
}

Cloud:

View code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;

namespace SendRaw
{
public partial class SendRaw : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void ButtonSendRaw_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 raw notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// Create the raw message.
string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<root>" +
"<Value1>" + TextBoxValue1.Text.ToString() + "<Value1>" +
"<Value2>" + TextBoxValue2.Text.ToString() + "<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");
//Possible batching interval values:
//"3":The message is delivered by the push notification service immediately.
//"13":The message is delivered by the push notification service within 450 seconds.
//"23":The message is delivered by the push notification service within 900 seconds.
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();
}
}

}
}

Running effect:

Channel URI:

Mobile Terminal:

Cloud:

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.