简体   繁体   中英

GCM push notification with C# asp.net giving null as notification in android devices

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.

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\\"}}";

In Android OnMessage(in GCMIntent service) write folowin line

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

Happy Coading:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM