GCM push notification with C# asp.net giving null

2019-07-14 07:48发布

问题:

I am creating a class in C# which has a method to send push notification in android using GCM. The method is working well and also giving response from google as success. But in the android emulator the notification is coming as null. Here is the code I am using,

public void NotifyTest(string regId)
    {
        var applicationID = "AIza*************"; 

        var SENDER_ID = "xxxxxxxxxx"; 
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
        httpWebRequest.Headers.Add(string.Format("Sender: key={0}", SENDER_ID));
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"registration_ids\":[\""+ regId +"\"]," +
                        "\"data\": { \"score\" : \"1234\"}}";
            Console.WriteLine(json);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                Console.WriteLine(result);
            }
        }
    }

The code is working without any errors and returning the response from Google too. Please let me know the suggestions.

回答1:

You need to replace the json string as below & modify your Android code for the get message & name.

string json = "{\"registration_ids\":[\"" + regId + "\"]," + "\"data\": { \"message\" : \"1234\", \"name\": \"Arvind Sharma\"}}";



回答2:

In Android OnMessage(in GCMIntent service) write folowin line

  String message = intent.getStringExtra("score");

Happy Coading:)