GCM Push Notification with Asp.Net

前端 未结 5 1144
谎友^
谎友^ 2020-11-30 03:25

As you may have seen, Google is migrating its Push Notification System.

http://developer.android.com/guide/google/gcm/c2dm.html

Is there any sample or guide

5条回答
  •  醉话见心
    2020-11-30 04:16

    A while back I had been playing around with C2DM to send push notifications. I altered my code as per changes mentioned on this page: http://developer.android.com/guide/google/gcm/c2dm.html#server to make use for GCM service:

    Private Sub btnPush_Click(sender As Object, e As System.EventArgs) Handles btnPush.Click
        lblResponse.Text = SendNotification(AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA)
    End Sub
    

    My SendNotification function:

    Private Function SendNotification(ByVal authstring As String) As String
        ServicePointManager.ServerCertificateValidationCallback = Function(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) True
        Dim request As WebRequest = WebRequest.Create("https://android.googleapis.com/gcm/send")
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        request.Headers.Add(String.Format("Authorization: key={0}", authstring))
        Dim collaspeKey As String = Guid.NewGuid().ToString("n")
        Dim postData As String = String.Format("registration_id={0}&data.payload={1}&collapse_key={2}", deviceList.SelectedValue, txtPayload.Text, collaspeKey)
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()
        Dim response As WebResponse = request.GetResponse()
        dataStream = response.GetResponseStream()
        Dim reader As New StreamReader(dataStream)
        Dim responseFromServer As String = reader.ReadToEnd()
        reader.Close()
        dataStream.Close()
        response.Close()
    
        Return responseFromServer
    End Function
    

    It seems that GCM does not require you to authenticate against Google to obtain an auth key (as the case was with C2DM). Instead, you'll require an API key which is being passed to the SendNotification function. This page should help you get your API key set up: http://developer.android.com/guide/google/gcm/gs.html

    The code for my web form is below just in case:

    Eclipse AVD My Phone 1 My Phone 2



    As for creating your Android app to receiving the push notifications, check out this link: http://developer.android.com/guide/google/gcm/gs.html#android-app

    Don't forget to import System.Net, System.IO, System.Security.Cryptography.X509Certificates and System.Net.Security.

提交回复
热议问题