Sunday, May 19, 2013

Push Messages to GCM server using c#.net application (server side).

      Google Cloud Messaging (GCM) is a service that helps developers send data from servers to their Android applications on Android devices. Google Cloud Messaging (GCM) replaces the beta version of Android Cloud to Device Messaging (C2DM).
The free service has the ability to send a lightweight message informing the Android application of new data to be fetched from the server. Larger messages can be sent with up to 4 KB of payload data.

This tutorial explains about how to send message to GCM server using .net application. Then GCM server pushes the messages to particular devices.
1. First, create new web application (File/new/website/Asp.Net Empty web site).
2. Design your page like below



 Data Post Format


{   "collapse_key": "score_update",     "time_to_live": 108,       "delay_while_idle": true,
     "data": {
     "score": "223/3",
     "time": "14:13.2252"
                  },
     "registration_ids":["4", "8", "12", "16", "25", "38"]
}

collapse_key             = Message type                                                                          
time_to_live               = How long (in seconds) the message should be kept on     
                                                              GCM storage if the device is offline (default:4 weeks).       
delay_while_idle       = It indicates that the message should not be sent                  
                                                                immediately if the device is idle. The server will                 
                                                                wait for the device to become active, and then only the     
                                                                last message for each collapse_key value will be sent      
data                             = Message Paylod.                                                                                            
 registration_ids         = A string array with the list of devices (registration IDs)
                                                               receiving the message. It must contain at least 1 and at     
                                                               most 1000 registration IDs. To send a multicast message,    
                                                               you must use JSON. 


3. Write a method in OnClick() function of send button. The code follows


protected void SubmitButton1_Click(object sender, EventArgs e)                                                             
        {                                                                                                                                                  
         AndroidPush();  // calling android push method                                                                               
        }                                                                                                                                                  
                                                                                                                                                           
//Android push message to GCM server method                                                                                       
private void AndroidPush()                                                                                                                      
        {                                                                                                                                                   
 // your RegistrationID paste here which is received from GCM server.                                                               
       string regId = "APA91bG_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_V6hO2liMx-                   
                           eIGAbG2cR4DiIgm5Q";                                                                                              
 // applicationID means google Api key                                                                                                     
       var applicationID = "AIzaSyDScBxxxxxxxxxxxxxxxxxxxpv66IfgA";                                                         
// SENDER_ID is nothing but your ProjectID (from API Console- google code)//                                          
                var SENDER_ID = "77xxxxx625";                                                                                            

                var value = Text1.Text; //message text box                                                                               

                WebRequest tRequest;                                                                                                           

                tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");                             

                tRequest.Method = "post";                                                                                                       

                tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";                             

                tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));                              

               tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));                                         

         //Data post to server                                                                                                                                         
         string postData =     
              "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="         
               + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" +      
                  regId + ""; 


                                                                                                            

                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);                                                

                tRequest.ContentLength = byteArray.Length;                                                                  

               Stream dataStream = tRequest.GetRequestStream();                                                    

               dataStream.Write(byteArray, 0, byteArray.Length);                                                          

               dataStream.Close();

               WebResponse tResponse = tRequest.GetResponse();                                                  

               dataStream = tResponse.GetResponseStream();                                                            

              StreamReader tReader = new StreamReader(dataStream);                                          

              String sResponseFromServer = tReader.ReadToEnd();   //Get response from GCM server.

               Label3.Text = sResponseFromServer;      //Assigning GCM response to Label text 

                 tReader.Close();                                                                                                                    

                dataStream.Close();                                                                                                             
                tResponse.Close();                                                                                                              
               }                                            


Note: The above code is for sending single regID. To send mutiple regID's, you can send up-to 1000 regID's to google server once or you can loop the code.  
                                  
4. After clicking send button you will get response from GCM server like id=343kdhgsy4y32i42@adfgd. It means that you successfully sent message to GCM server.


  You will get message in your mobile like this..


For GCM Client side tutorial click here. Download the GCM C# server side code below.
                                     
                                                        
                         
                                     
                                      

Enjoy coding.....




200 comments:

  1. It helped me a lot. thanks..

    ReplyDelete
  2. Hi could you provide me with the actual .sln package.

    ReplyDelete
  3. Appreciate your generosity on this knowledge, nice if you would youtube this tutorial.

    ReplyDelete
  4. Hi Tej,
    can you tell what is the difference of using WCF instead of ASP Web Application? And what is the most suitable method? Thanks.

    ReplyDelete
    Replies
    1. According to your requirement you choose it.For example, I want to send messages manually(multiple admins can use it). So, i choose Web application. You can send messages via WCF also. Its a wonderful service to use and more secure than earlier one. If you want auto generated messaging system then you go for WCF.

      Delete

  5. hi Tej Prakash its a great post for .net person who are working in android too like me. its very helpful for me.
    i am new in android so don't know so much. you mentioned about Registration ID which is received from GCM server.where i will get this registration id?? is it come into my mail account or any where else. could you provide me with the .sln package.
    my mail id is manishbadal18@gmail.com

    i will be very thankful to you if you will help.

    waiting for positive response.

    ReplyDelete
    Replies
    1. Hi mani,
      You will get the Registration Id to your mobile When you start-up the application (i.e only when MainActivity code runs) . Look out the MainActivity(client side code),there i am catching the Registration-ID which is provided by GCM server and saving the registration-ID into the database(refer SERVERUtilities.java).All the code i have given in client side tutorial. Just change the SERVICE_URL in CommonUtilities.java to save data in your DB.
      please follow below link...
      http://www.tejaprakash.com/2013/02/google-cloud-messaging-for-android.html

      Delete
  6. Hi Tej,

    Thank you for the useful post. I have question about handling the registration request on the server side:
    1- How can I identify and capture the request so I can put that in my db?
    2- Does it come in URL or what?

    Many thanks.

    ReplyDelete
    Replies
    1. There is no registration required in server side. You have to sent just message request to server. Android user will register in GCM server and sent regID to your own DB.
      thanks......

      Delete
  7. Hi Tej,

    Thanks for your wonderful article.
    Can you send me your actual solution?
    My mailid -> rajibmvp@gmail.com

    ReplyDelete
  8. Hi Tej , Can you plz give me .sln project ?

    ReplyDelete
  9. My Email Id : nikunj.ce31@gmail.com

    ReplyDelete
    Replies
    1. Download from here: https://www.dropbox.com/s/cs7ibm7q1ir20gy/AndroidPushNotifications.zip

      Delete
    2. I really need it. you can update link?. it's die! thanks you.

      Delete
    3. this is my email, or you can send link download project AndroidPushNotifications.zip for me. hjhj

      Delete
  10. Hello Tej....can you please give me the database script fot this project ???

    ReplyDelete
    Replies
    1. Hi Niks,
      Create a table in DB which is used to store and retrieve the Registration-id.
      Write Stored-procedure to get all Reg-Id's(I have used SQL server).

      Ex: Select RegID from TableNAME.

      Delete
  11. Hi Tej,

    I am getting the below error The remote name could not be resolved: 'android.googleapis.com'.

    can u pls advise on this.

    ReplyDelete
    Replies
    1. Hi Easwaran,
      Your sending bad request or incorrect data to the server.Please check your URL format and data that your sending to server.

      Delete
    2. I had the same error, but in the server I had a bad DNS ip, the entire server doesn't had internet.

      Delete
  12. Hi Tej,

    below is the code that i have used...not sure where the issue is.....

    // your RegistrationID paste here which is received from GCM server.
    string regId = "";
    // applicationID means google Api key
    var applicationID = "AIzaSyCqxI79xHHggignZvtqOA0oFnjB7M1gmac";
    // SENDER_ID is nothing but your ProjectID (from API Console- google code)//
    var SENDER_ID = "637808462189:";

    var value = "Test-Server Side";//message text box


    WebRequest tRequest;

    tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");

    tRequest.Method = "post";

    tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";

    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));

    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

    //Data post to server
    string postData =
    "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
    + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" +
    regId + "";

    Console.WriteLine(postData);

    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    tRequest.ContentLength = byteArray.Length;

    Stream dataStream = tRequest.GetRequestStream();

    dataStream.Write(byteArray, 0, byteArray.Length);

    dataStream.Close();

    WebResponse tResponse = tRequest.GetResponse();

    dataStream = tResponse.GetResponseStream();

    StreamReader tReader = new StreamReader(dataStream);

    String sResponseFromServer = tReader.ReadToEnd(); //Get response from GCM server.

    TextBox1.Text = sResponseFromServer; //Assigning GCM response to Label text

    tReader.Close();

    dataStream.Close();
    tResponse.Close();
    }

    ReplyDelete
    Replies
    1. Hi Easwaran,
      Please check your API key and regId once. Are you sending empty regid to server? Make sure that you must send the regid to the server with the same SENDER_ID that you register in the GCM server earlier.

      Delete
  13. Thanks Tej

    is that mandatory to send the register id ? my understanding is if i send an empty register id, the notification would go to all the devices which has the application installed.

    ReplyDelete
    Replies
    1. Yes, it is mandatory.
      that's an bad idea.
      GCM server can't send the notifications without it because GCM server sends notifications to mobiles through RegID's.
      Each every mobile has unique ID. Every time GCM server checks with it.

      Delete
  14. how can i send notification to multiple users? how should i use registratiomids? in which format?

    ReplyDelete
    Replies
    1. Hi hetal,
      You can send messages to GCM server Upto 1000 users once. Get 1000 ID's once, arrange them in JSON format and send it as above.

      Delete
    2. Hi tej, can you plis give an example how to arrange the IDs in JSON format? thank you so much.

      Delete
  15. How can i know automatically that my blog or site is changed and if it has change then push notification send to device..?

    ReplyDelete
    Replies
    1. Hi Pratik,
      You will get response from GCM server after sending a push notification weather message sent fail or success. Then you have to handle your site with that response. Automatically it will not change the site.

      Delete
    2. Hi I am using the steps you mentioned above and notification sent successfully but the message is not appearing.

      Delete
    3. Hi manish,
      Make sure that your GCM Intent activity code(Android) is correct.
      In OnMessage method, you should use same parameter that you use in server side. e.g:message.
      String receivedata = intent.getStringExtra("message");

      Delete
  16. Sir could u help plz to write Webservice file .asmx because i have little bit knowledge about .net plz suggest me some website that describe webservices at initial level

    ReplyDelete
    Replies
    1. Hi Sumant,
      I have posted basic web-service here. please check it once.
      http://www.tejaprakash.com/2013/01/create-basic-web-service-using-dot-net.html

      Otherwise go for below stuff for basics
      http://www.w3schools.com/webservices/default.asp
      http://www.tutorialspoint.com/webservices/index.htm

      Delete
  17. Thank you!! It is working fine!!
    Is it possible to send the message to multiple devices using the same WebRequest?

    ReplyDelete
  18. Yes, it is possible to send multiple message.

    ReplyDelete
  19. tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
    tRequest.Method = "post";
    tRequest.ContentType = "application/json";
    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

    string key = "{{ \"collapse_key\": \"mensaje_update\", \"time_to_live\": 108,\"delay_while_idle\": true,";
    string datos = "\"data\": {{\"message\": \"" + value + "\",\"time\": \"" + System.DateTime.Now.ToString() + "\"}},";
    string registration_ids = "\"registration_ids\":[\"" + regId + "\"]}}";
    string postData = key + datos + registration_ids;

    //Now I want to send the message to one device, for testing purposes but I am receiving 401 exception. I have read that in c# \"==" and {{=={

    Console.WriteLine(postData);
    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    tRequest.ContentLength = byteArray.Length;
    Stream dataStream = tRequest.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    WebResponse tResponse = tRequest.GetResponse();
    dataStream = tResponse.GetResponseStream();
    StreamReader tReader = new StreamReader(dataStream);
    String sResponseFromServer = tReader.ReadToEnd();

    What am I missing?

    ReplyDelete
    Replies
    1. Exception 401 means an error authenticating the sender account. Posting data format to GCM Server is wrong. please check the above tutorial once.

      Delete
    2. I followed your tutorial and I am able to send messages to one device using your aproach, plain text. Everything perfect. But I want to send the messages to multiple devices so I read in google GCM pages if the objective is to send multiple devices the data posted must be in Json format. But I dont know how to do it. I will post here when I find the solution

      Delete
    3. I deleted the double brackets {{-}} and replaced for single ones {-} and deleted all space in the json string. Now is working ok. Thank you!

      Delete
    4. I am having problems in two testing devices with Android 2.3 Gingerbread. OnReceive method in GcmBroadcastReceiver class is fired but the messagetype is null , and it neither has contents. I supose messagetype is filled in gcm server.

      I added these lines to the manifest:



      Delete
    5. Hi Pixue,
      n GCMIntentService class, place the sample message like below.
      String message = getString(R.string.gcm_message);
      If it is working correctly, then change it actual one like below.
      String message = intent.getStringExtra("message");
      If it is not working then check the message parameter in both server and client should be same. Again it is not working then check your server side code once.

      Delete
    6. It is working again, I had a problem in the manifest file. Thank you!!

      Delete
  20. This comment has been removed by the author.

    ReplyDelete
  21. String receivedata = intent.getStringExtra("message");
    Getting null data plz help

    ReplyDelete
    Replies
    1. Make sure that server side & client side should be same named parameters. Ex:message.

      Delete
  22. not able to download code from the given link.pls send it to my mail id sathyacsermd@gmail.com

    ReplyDelete
    Replies
    1. Hi sathya,
      try this......https://app.box.com/s/01ipxjbs7d24b3et6vvw

      Delete
    2. Hi Tej,
      i am getting socket exception when i try to send the msg.
      do i want to give same url which u given in webrequest.create?
      i think my application not able to connect gcm server.how to resolve it?
      pls reply soon.thanks

      Delete
    3. Hi Sathya,
      Yes, you have to give same URL.

      Delete
    4. could u tell me why socket exception is occuring?

      Delete
    5. getting unable to connect to the server
      in this line Stream dataStream = tRequest.GetRequestStream();

      Delete
    6. socket exception occurs when connection establish failed. Follow the above code just change the SENDER ID and Application Id. you will get it for sure.

      Delete
    7. yes Tej,i tryed with the same code.
      i changed only the sender id,app id,reg id.
      same exception throwing..any idea?

      Delete
    8. hi Tej,
      now i am able to send notification to my device.bcz of internet problem i was getting exception.
      can u give me the json format to send to multiple devices at a time.

      Delete
  23. Hi Tej,
    even i tryed this link also..but its saying "This webpage is not available".i am working similar kind of this project.so i need ur help.

    ReplyDelete
  24. Hi Tej, I have an android application and a Webservice that is configured at my server for that very android application. I want to use GCM to send push notification to my android application from my server. Can you please list down the steps that I need to follow to achieve this thing.

    ReplyDelete
    Replies
    1. Hi danish,
      Follow GCM Client tutorial. you will get an basic idea-http://www.tejaprakash.com/2013/02/google-cloud-messaging-for-android.html

      If you don't get that then ask me your doubts.

      Delete
  25. unable to send multiple devices.Can you please post some sample code

    ReplyDelete
    Replies
    1. Hi rams,
      You can kept upto 1000 regID's in Json format or you can loop the code.

      Delete
  26. I am unable to send multiple devices.Can you please post some sample code.

    please see mycode bellow
    var applicationID = "AIzaSyCrLKQuISHXHu_0A63Uq0zkdI7sIOg73JA";
    List regids = new List() { "APA91bGvYFE01W6jsnb5BNJzNT1lxdfGgzftkUFqtLy4bfERnezXNlC8QeFim-qa-qByczvD6osMZPfkkW49QGGpF5PtJFvty6ViKmVkX9ialY-W_iorjKwA8oWtDwQeEvJ-hcSsR5eFA23bGxkTjxtAET6iCmoC8w", "APA91bGvYFE01W6jsnb5BNJzNT1lxdfGgzftkUFqtLy4bfERnezXNlC8QeFim-qa-qByczvD6osMZPfkkW49QGGpF5PtJFvty6ViKmVkX9ialY-W_iorjKwA8oWtDwQeEvJ-hcSsR5eFA23bGxkTjxtAET6iCmoC8w" };

    System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
    new System.Web.Script.Serialization.JavaScriptSerializer();
    var regid = jSearializer.Serialize(regids);

    var SENDER_ID = "1004843660144";
    var value = Text1.Text;
    WebRequest tRequest;
    tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
    tRequest.Method = "post";
    tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));

    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

    //Data_Post Format
    //string postData = "{'collapse_key' : 'demo', 'registration_id': [ '" + regId + "' ],
    //'data': {'message': '" + Label1.Text + "'},'time_to_live' : '3' }";


    string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
    + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regid + "";


    Console.WriteLine(postData);
    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    tRequest.ContentLength = byteArray.Length;

    Stream dataStream = tRequest.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    WebResponse tResponse = tRequest.GetResponse();

    dataStream = tResponse.GetResponseStream();

    StreamReader tReader = new StreamReader(dataStream);

    String sResponseFromServer = tReader.ReadToEnd();

    Label3.Text = sResponseFromServer; //printing response from GCM server.
    tReader.Close();
    dataStream.Close();
    tResponse.Close();

    ReplyDelete
  27. by passing json data I am getting invalid registration id error.

    ReplyDelete
  28. Hi Tej,

    I have tried your solution and its working fine, Thank you.
    1> Have you worked with the same kind of solution for IOS?
    2> How about sending multiple registration ids, can you provide the syntax for that(the json data).



    ReplyDelete
    Replies
    1. Yes, I have done for IOS using Moon-apn s. Simply you can loop the code for multiple.

      Delete
  29. Hello ,

    When I am using your code in localhost and sending the message the device receives it.
    but when I am hosting the page to my server and than try to send than it says Error=InvalidRegistration

    can you please help

    ReplyDelete
    Replies
    1. Hi Meghal,
      Your sender Id or Registration Id may be wrong. Send valid ID's to GCM server.

      Delete
    2. Hello Tej ,

      But when I am downloading the same page from my server and run into local pc, at that time I get the notification.
      without changing a single line.

      I have the same page on my server and in local but in server I get the above error where as in local I get the the notification in my device.

      Delete
  30. hi..
    Can you have an application for receiving message from device to pc with asp.net web application. I want to create web application which received messages from devices and display it like popup on dashboard or home page of my web application automatically when message is received. Please reply as early as possible.

    Thanks

    ReplyDelete
    Replies
    1. Hi samir, I haven't done it. But we can do it in similar way. Send status(received) from device to your Server through some service. And you can use SignalR(http://signalr.net/) to receive the status in Web Application.

      Delete
  31. Hi,
    Im new in android development. I'm having an issue of retrieving RegID from sql database.

    I tried to trace the value from
    string regID = dsregID.Tables[0].Columns["RegID"].ToString();

    And i got the value "RegID" but not the actual registrationID i stored in the database.

    What am i missing here?

    ReplyDelete
    Replies
    1. This is the stored_procedure to get the table content

      CREATE PROCEDURE [dbo].[Proc_PushGetRegId]

      AS
      BEGIN
      Select RegID from AndroidRegId
      END

      Delete
    2. Hi Kow, On which base, your retrieving the regID?
      For example, I am retrieving RegID for particular USER (below query).
      Select RegID from AndroidRegId where UserID=@userid

      Delete
    3. I wanted to try retrieve the 1st content from the table.

      Delete
    4. how your are saving records in DB?

      Delete
  32. This comment has been removed by the author.

    ReplyDelete
  33. I solved it! This was the code that works for me. Now i just need to loop on the Rows[i] for multiple device. Thx for the awsome tutorial anyway!
    string regId = dsregID.Tables[0].Rows[0]["RegID"].ToString();

    ReplyDelete
  34. Tej can you please tell ,me how to send registration id that i recieved from GCM server to my local .net server?

    ReplyDelete
    Replies
    1. Hi Ahmed, you can use Web-service(SOAP or REST). You can find Url like ''http://10.0.2.2:10739/GCM-server.asmx/PostRegistration-Id'' in my CommonUtilities.java(Android-Client code). Just replace your service link there. It works for you.

      Delete
    2. In your server utilities class i send reg id to a method like this

      public static void postData(String rid)
      {
      try
      {

      rslt="START";
      Caller c=new Caller();
      c.call="post";
      c.address=rid;

      c.join();
      c.start();

      while(rslt=="START") {
      try {
      Thread.sleep(10);
      }catch(Exception ex) {
      }

      }

      }catch(Exception ex) {

      }
      }


      then in caller.java class i do following code

      public class Caller extends Thread
      {
      public String call;
      public CallSoap cs;

      public String address;
      public void run(){
      try
      {
      if(call=="post")
      {
      cs=new CallSoap();
      String resp=cs.postData(address);
      ServerUtilities.rslt=resp;
      }

      }catch(Exception ex)
      {}
      }

      }

      at last in callsoap.java

      public final String WSDL_TARGET_NAMESPACE = "http://192.168.1.101/AndroidPushNotifications/";



      public final String SOAP_ADDRESS = "http://192.168.1.101/AndroidPushNotifications/gcm1.asmx";
      public CallSoap()
      {
      }

      public String postData(String RID)
      {

      SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,"PostRegistrationId");
      PropertyInfo pi=new PropertyInfo();
      pi.setName("id");
      pi.setValue(RID);
      pi.setType(String.class);
      request.addProperty(pi);


      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
      SoapEnvelope.VER11);
      envelope.dotNet = true;

      envelope.setOutputSoapObject(request);

      HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
      String response=null;
      try
      {
      httpTransport.call("http://192.168.1.101/AndroidPushNotifications/PostRegistrationId", envelope);
      response = envelope.getResponse().toString();
      }
      catch (Exception exception)
      {
      response= exception.toString();
      }
      return response;
      }

      I am too confused with this i am using the same coding to access another webservice that is on live server and is working fine ?? Why this not work for me on local server Kindly help me .

      Delete
    3. where as PostRegistrationId is the method name of my webservice that i want to invoke.

      Delete
    4. For online server is working fine right? It's problem in your local system or server? Then I think you have problem with the service URL. You have to use '10.0.2.2:portNo.' instead of your 'localhost' or 'IP address''.

      Delete
    5. hi tej i am now facing another problem. i have an emulator with following specifications. google api 18 , 512 ram but it is too slow. it takes more then 1 hour to start . how i can fix this

      Delete
    6. Use snapshot,it improves the boost time or use intel X86 hardware accelerator. Actually, it should not take upto 1 hour to start. I think your PC has some trouble.

      Delete
  35. Helloo Tej please is there and php version for the server side code ? Thanks in advance

    ReplyDelete
    Replies
    1. Hi Ali, I don't have php version. But you can find php side code easily on google search.

      Delete
  36. Hai Tej ,Please help me , i am getting error as (The remote server returned an error: (401) Unauthorized.) what i did mistake?


    protected void btn_Send_Click(object sender, EventArgs e)
    {

    string regId = "APA91bEoLPR9SkMpLgA5iHFhS-USOTFSm7cNGxCJGmuSMAa6adQSq2r6-2zsUw6NdVIblig2LV5xCkyQa4uaKmmga-Dd1yn6aitQ9V5MPvGmeMDBTyDwuDS8JAFI2t54oCpd2i4DfittxD3HIKGb4CHNwulrjoxNUQ";
    var applicationID = "AIzaSyBVD4k4hr3hyk9UE82eiZNMkqP4MsCMNs0";
    var SENDER_ID = "123795843006";
    var value =txtBox_Msg.Text; //message text box
    WebRequest tRequest;

    tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");

    tRequest.Method = "post";

    tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";

    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));

    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

    string postData =
    "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
    + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" +
    regId + "";

    Console.WriteLine(postData);



    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    tRequest.ContentLength = byteArray.Length;

    Stream dataStream = tRequest.GetRequestStream();

    dataStream.Write(byteArray, 0, byteArray.Length);

    dataStream.Close();

    WebResponse tResponse = tRequest.GetResponse();

    dataStream = tResponse.GetResponseStream();

    StreamReader tReader = new StreamReader(dataStream);

    String sResponseFromServer = tReader.ReadToEnd(); //Get response from GCM server.

    lbl1.Text= sResponseFromServer; //Assigning GCM response to Label text

    tReader.Close();

    dataStream.Close();
    tResponse.Close();
    }

    ReplyDelete
    Replies
    1. Hi sateesh, exception 401 means an error authenticating the sender account. You may sending wrong regID, appID or senderID to the server. Check once.

      Delete
    2. Thanks Tej Prakash i solved that but i got one more error as (Error=MismatchSenderId) How to solve this?

      Delete
    3. What you sending the RegID to GCM server is not registered with your SENDERID. So that you are getting MISMATCHED ERROR.

      Delete
    4. This comment has been removed by the author.

      Delete
    5. This comment has been removed by the author.

      Delete
    6. 1. It's easy to arrange in Json string. You can send up-to 1000 Regid's to GCM server once like {1,2,3......}.
      2. You have to provide USERID to get specific user RegId.

      Delete
    7. This comment has been removed by the author.

      Delete
    8. hi Tej, am getting unauthorized (401) in WebResponse tResponse = tRequest.GetResponse(); line

      Delete
  37. I tried a lot and still get error " The remote server returned an error: (401) Unauthorized. "
    I'm sure tha applicationID (Key for browser applications), SENDER_ID (Project Number), and regId is correct.

    Error in line WebResponse tResponse = tRequest.GetResponse();

    ReplyDelete
  38. Hi Tej,
    In the status bar, How can we show the message count when there are multiple message at the same time?

    ReplyDelete
    Replies
    1. Hi manjunath, i think GCM server won't give you count of messages. But, you can customize your status bar. Follow this link for basic idea http://developer.android.com/guide/topics/ui/notifiers/notifications.html

      Delete
  39. Sir i make a database many user in this table he send message to other user let say me send to specific user ali how to identify of specific user to send only Ali how to use GCM for android + web service plz reply me fiazsial@gmail.com if any code for this propose
    Thanks

    ReplyDelete
    Replies
    1. Hi Fiaz, get the record based on User-Id. And send to particular user.

      Delete
  40. Hi Tej, will give me the complete code. I downloaded which is there, I am getting error at WebResponse tResponse = tRequest.GetResponse(); this line, The remote server returned an error: (401) Unauthorized. I am using everything which we required. how to do resolve this? Please help me. thank you

    ReplyDelete
    Replies
    1. venu3699@gmail.com my id

      Delete
    2. Hi Venu, please check your RegID and API key once. You have to create new keys one if not. Follow this tutorial for creating keys: http://www.tejaprakash.com/2013/02/google-cloud-messaging-for-android.html

      Delete
    3. Hi gone through your url, I am using Titanium Studio, not eclips, in android sdk, I dont have Google Cloud Messaging for Android Library, how to install it.
      Thanks in advance

      Delete
    4. Hi venu, i haven't used Titanium Studio. Sorry, i don't know about it. But i will search about it. If i found any information then i will mail you.

      Delete
  41. Hi Tej, I tried it again now I am getting Error=InvalidRegistration in the place of GCM server responce? what wrong I am doing?

    ReplyDelete
  42. Hi Tej, if I have to send message_Type parameter how to do that? like my message should show like is it Alert or Warning or Information. please do help

    thanks in advance

    ReplyDelete
    Replies
    1. Hi Venu, you can use "collapse_key" for defining the message type. Another way, you can pass parameter in 'data' like data:{ type: "alert", message:"hiiiii"}.

      Delete
  43. Replies
    1. Hi Master, your Android mobile receives the RegistrationID from Google.
      For more info visit: http://www.tejaprakash.com/2013/02/google-cloud-messaging-for-android.html

      Delete
  44. Hi Tej,
    Can you give sample code for sending push notifications to multiple registered ids at a time by clicking a button....

    ReplyDelete
  45. Hi Tej,
    I am unable to send multiple devices.Can you please post some sample code for me
    Here I attached My CODE pls Tell me am i did wrong

    string GoogleAppID = "AIzaSyBwOlaJn-YCzygAN7hwXgH4xw44FAh0hc0";
    string SENDER_ID = "999104283613";
    string[] arr1 = new string[objSendMessage.mbrId.Length];
    string stringregIds = null;
    int i = 0;
    foreach (Guid gid in objSendMessage.mbrId)
    {
    MemberInvitation.GetDevice objgetdevice = InvitationManager.GetDeviceIDforPushNotification(gid);
    if (objgetdevice.strDeviceID != null)
    {
    arr1[i] = objgetdevice.strDeviceID;
    i++;
    }
    }

    stringregIds = string.Join("\",\"", arr1);
    string s = "";
    string s1 = "\",\"";
    string s2 = "\",\"\",\"";

    if (stringregIds != s && stringregIds != s1 && stringregIds != s2)
    {
    UserDetails objuserdetails = UserManager.GetMemberBasicInformation(new Guid(HttpContext.Current.Session["MemberID"].ToString()));
    string value = objuserdetails.strFirstName + " " + " sent message";
    WebRequest tRequest;
    tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
    tRequest.Method = "post";
    tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
    string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    tRequest.ContentLength = byteArray.Length;
    Stream dataStream = tRequest.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse tResponse = tRequest.GetResponse();
    dataStream = tResponse.GetResponseStream();
    StreamReader tReader = new StreamReader(dataStream);
    String sResponseFromServer = tReader.ReadToEnd();
    string returnresult = sResponseFromServer;
    //int id = Convert.ToInt16(returnresult);
    tReader.Close();
    dataStream.Close();
    tResponse.Close();
    }

    this is my code
    But Notification Not Comming
    Pls tell me What i did wrong


    madhub24@gmail.com this is my email id
    pls inform me

    ReplyDelete
  46. Hi Tej,
    I am unable to send multiple devices.Can you please post some sample code for me
    Here I attached My CODE pls Tell me am i did wrong

    string GoogleAppID = "AIzaSyBwOlaJn-YCzygAN7hwXgH4xw44FAh0hc0";
    string SENDER_ID = "999104283613";
    string[] arr1 = new string[objSendMessage.mbrId.Length];
    string stringregIds = null;
    int i = 0;
    foreach (Guid gid in objSendMessage.mbrId)
    {
    MemberInvitation.GetDevice objgetdevice = InvitationManager.GetDeviceIDforPushNotification(gid);
    if (objgetdevice.strDeviceID != null)
    {
    arr1[i] = objgetdevice.strDeviceID;
    i++;
    }
    }

    stringregIds = string.Join("\",\"", arr1);
    string s = "";
    string s1 = "\",\"";
    string s2 = "\",\"\",\"";

    if (stringregIds != s && stringregIds != s1 && stringregIds != s2)
    {
    UserDetails objuserdetails = UserManager.GetMemberBasicInformation(new Guid(HttpContext.Current.Session["MemberID"].ToString()));
    string value = objuserdetails.strFirstName + " " + " sent message";
    WebRequest tRequest;
    tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
    tRequest.Method = "post";
    tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
    string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    tRequest.ContentLength = byteArray.Length;
    Stream dataStream = tRequest.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse tResponse = tRequest.GetResponse();
    dataStream = tResponse.GetResponseStream();
    StreamReader tReader = new StreamReader(dataStream);
    String sResponseFromServer = tReader.ReadToEnd();
    string returnresult = sResponseFromServer;
    //int id = Convert.ToInt16(returnresult);
    tReader.Close();
    dataStream.Close();
    tResponse.Close();
    }

    this is my code
    But Notification Not Comming
    Pls tell me What i did wrong


    madhub24@gmail.com this is my email id
    pls inform me

    ReplyDelete
  47. Hi,
    I have a website and I am working on this website's android application.

    I am using asmx web service (.net). when data is inserted to website's database ,I want to send this data to android devices. How can handle this issue?

    Thanks in advance.

    ReplyDelete
  48. Hi could you provide me with the actual .sln package.
    my mail id is haiajster@gmail.com

    ReplyDelete
  49. Hi tej i m getting notfication as message but its not giving me as notification like its comes in whatsapp applications. It just sends message

    ReplyDelete
  50. Hi I am getting an error at this point
    WebResponse tResponse = tRequest.GetResponse();

    The remote server returned an error 401: Unauthorized

    ReplyDelete
  51. Hello Tej Prakash Rao Peddineni Sir,
    Please help me asap
    This line gives
    WebResponse tResponse = tRequest.GetResponse();
    the following error :
    "The remote server returned an error 401: Unauthorized"

    1 month ago it is working fine , but from last few days 401 error.
    Please help me asap.

    Regards
    Rohin Sharma

    ReplyDelete
  52. Hi, Thank you for the tutorial, but i have a problem, when i use your example with my data(sender_id, registration_id, apikey), the server returned me: error=invalidregistration. Help me please!!! My email is: jossimaram92@gmail.com.

    ReplyDelete
  53. Hi Tej, Many many thanks for very helpful artical but could you please add how can I send notification to multiple devices in 1 requrest?

    ReplyDelete
    Replies
    1. Hi Tej, I got my answer http://stackoverflow.com/questions/22486192/gcm-error-missingregistration-sending-messages-via-json

      Delete
  54. where to get RegistrationID??? still not sure

    ReplyDelete
  55. how to implement deepl linking with this code

    ReplyDelete
  56. Hi tej, Please send db script of the app. Thank You

    ReplyDelete
  57. Sir can u send me the solution package? i got a problem to my project and i badly need it.. thank you. breeve.antonio@gmail.com

    ReplyDelete
  58. Hi, Can we get success or failure status against each mobile registered id when we send one push notification in bulk ( by looping the code) . Currently I am sending one push message to few thousands mobiles. I am getting response in cumulative for each batch and not as individual response.

    ReplyDelete
  59. Check Out
    http://stackoverflow.com/questions/13929790/ive-got-this-response-from-the-gcm-server-success1-but-the-notification-no
    for sending message to Multiple Registration IDs (Question was my solution this time)

    ReplyDelete
  60. How to send image via push notification using c#

    ReplyDelete
    Replies
    1. Hi sujith,

      There is a 4Kb limit for the each message in GCM. You can't send the data beyond the limit. You can send the image Urls Or you can send image through base64 encoded format but not exceeding the limit.

      Ex: data.message= { "message" : "demo msg",
      "image": "imageUrl/base64 encode"
      }

      Delete
  61. hi tej,

    Please send db script of this app

    i need stored procedure and database table..field
    my mail id is elaunch.pankaj@gmail.com

    ReplyDelete
  62. WebResponse tResponse = tRequest.GetResponse();

    Give Error :=> The remote server returned an error: (401) Unauthorized.

    ReplyDelete
    Replies
    1. Hi Sumit,

      Make sure that google api key and senderID are correct.

      Delete
  63. Notification recieved on my android device is blank only with app icon and its name,not displaying message ..tried with json data format too.

    ReplyDelete
    Replies
    1. Hi Ansari,
      Make sure that the message attribute name in data post(server side) and intent get string name in OnMessage method in the GCMIntentService.java class(Android application) should be same.


      Delete
  64. Hello Tej.

    I am using your code to send push notification. but i am getting error : InvalidRegistration. I am confused how to get RegistrationID. I am using a software called DeviceID which provides me device id of my android mobile. and i m using this
    Device ID as RegistrationID. Can you please explain me how to get RegistrationID.

    ReplyDelete
    Replies
    1. Hi Akhilesh,
      You need to sent the valid Registration ID. GCM RegId is different from DeviceId. You need to generate the RegID from the Android application. Please refer the link http://www.tejaprakash.com/2013/02/google-cloud-messaging-for-android.html

      Delete
    2. You mean that registrationID from my app.

      Delete
  65. I have to design app so that we can get registrationid of device. Can we done it by creating a registration for users, to register before using the app so that we can get their registrationid.

    ReplyDelete
    Replies
    1. Yes, you to need get it from app. But I don't know about the registration before the creation of app.

      Delete
  66. Dear Tej
    I have got Registration id which is something like "APA91bGKRMzGGrE8YWfLVBs9juTsGnzCtAjaqvgwdVMRDn3HQleGRNdsZfUwDSJWdYpHbyASox4PqvEfE40GcKq516D2by1ImIHsxb2YzksvYkPh5zgU76cqZb_Orx-XxA8QNd3bpwGR" but when i was sending notification is produced Error MismatchSenderid

    ReplyDelete
    Replies
    1. Hi Akhliesh,
      That's an valid registration ID but check your senderID (i.e ProjectID in google console) is correct or not.

      Delete
    2. let me check and will tell you, thanks tej for helping me.

      Delete
  67. hello Tej,
    I am getting error on this line :
    Stream dataStream = tRequest.GetRequestStream();
    Error:
    This stream does not support seek operations.

    ReplyDelete
  68. Hello Tej
    how can we create server for sending push notification in c#

    ReplyDelete
    Replies
    1. I didn't get you what you mean. But you can use a windows service or schedule jobs in server.

      Delete
  69. Hi tej

    AppName(Title) not showing ...i am using same code. pls help

    ReplyDelete
  70. hello frnd i get the error when i click on button

    error...."error=MismatchSenderId"

    ReplyDelete
    Replies
    1. Hi Piyush,
      Please check your Sender Id and RegID. Sometimes RegID may expires.

      Delete
    2. ohk will let u know after check regid ..thankzz for yr reply...

      Delete
    3. done tej prakash rao....there is an reg id prblem only..thankzzz

      Delete
  71. hello sir me develope app in this information come to db its developed in .net webservice file and software also in .net

    i want when i update any news then come notification on user mobile same as whats up plzzzzzzzzzzzz sir hellp i need urgent my whats up -8058199878 and give your num.. i hope u help me thanx sir

    ReplyDelete
    Replies
    1. Hi,
      Write a service to save the notifications into DB. Use that service in your Mobile app when notification arrives OR Save the messages into your DB when making a sending request to GCM server and get the list of notifications of particular user on app login/open. Display the list.

      Delete
  72. helloo tej prakash rao ...i need yr help ..how to send parameter in push notification....Like i am working on geo fence so i need to send the latitude and longitude to the device when the push is sent. I can send this in PHP. How is this possible with .net?

    ReplyDelete
  73. hello tej prakash rao what is your server_url for android application for GCM notification ?

    ReplyDelete
    Replies
    1. Hi, You need place your Web_service URL there.

      Delete
  74. Thanks for the great post! I understand sending SenderID from client app to GCM returns RegistrationID. This is needed to be able to send a message or notification from an app server later. Let's say 5 users install the app. Would each receive a unique RegistrationID, so the app server would need to know each of the RegistrationID's to be able to send a message to them later? If yes, how would I get all RegistrationID's of all users who have installed the app?

    ReplyDelete
    Replies
    1. Hi Oscar, RegistrationID is unique for every mobile and application. You need to save the RegistrationID into your database when user opens the app for first time.

      Delete
  75. Hi, I am receiving 'null' text. plz help.

    ReplyDelete
  76. Hi, I am receiving 'null' text. plz help.

    ReplyDelete
    Replies
    1. Hi Shah,
      Make sure that server side & client side should be same named parameter. Ex:message.

      Delete
  77. hello tej how are you.
    the code you have given i got an error: The remote server returned an error: (401) Unauthorized. on this line :
    WebResponse tResponse = tRequest.GetResponse();

    Can you please tell me the complete process of sending push notifcaiton. my mail id is :akhil_chndr@rediffmail.com

    ReplyDelete
  78. and please tell me how can we write server code for sending notifications

    ReplyDelete
  79. hello tej i am getting error MismatchSenderid

    ReplyDelete
  80. Hi Tej, i used your tutorial and i have same error (401) when i try to getResponse() and my regId, applicationID and SENDER_ID are OK (I checked and created again API Key without IP).
    But my question is, do i need a ssl certificate in my webserver to use this code?.
    Thanks.

    ReplyDelete
    Replies
    1. Hi, SSL certificate is not required to send notifications.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. I tried again after check the code (i use VB .Net ) and works!! Thanks Tej!

      Delete
  81. Bro I am getting this exception ==>

    System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A socket operation was attempted to an unreachable network [2607:f8b0:400a:807::200a]:443
    at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
    at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
    --- End of inner exception stack trace ---
    at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
    at System.Net.HttpWebRequest.GetRequestStream()

    ReplyDelete
  82. Como relaciono mi Android con la aplicacion que enviara el mensaje

    ReplyDelete
  83. Hello,
    How can I send image in push notification to android using asp.net and c#.

    ReplyDelete
    Replies
    1. Hi Samir,

      There is a 4Kb limit for the each message in GCM. You can't send the data beyond the limit. You can send the image Urls or you can send the image through base64 encoded format but not exceeding the limit.

      Ex: data.message= { "message" : "demo msg text",
      "image": "imageUrl/base64 encode"
      }

      Delete
  84. Hai. I'm getting below Error

    "The remote server returned an error: (401) Unauthorized."

    ReplyDelete
  85. i cannot understand why the above code gives socket exceptions when hosted on a web site panel . but it works fine on localhost.

    ReplyDelete
  86. hi
    how i get GCM registration Id

    ReplyDelete
  87. How to send telugu unicode notifications using this ? while sending telugu unicode text, its showing empty data.

    ReplyDelete
    Replies
    1. Hi Lokesh,
      Encode the text message/notification into html content and then send to GCM server.
      In Android application, decode the text and use any telugu font library to display the message.

      Delete
    2. Can you please send me a sample for encoding and decoding

      Delete
    3. I tried so many ways but i'm unable to get the telugu messages/notifications.
      Ok any way. Thank you

      Delete
  88. Hi,

    How to push multiline message . Please help

    ReplyDelete
  89. which db i have to use. or please send me sql script on my mail id mani007tiwari@yahoo.in

    ReplyDelete
  90. how we can get android app. which need to be installed.i have created my project and got key but i didnt get res id .

    ReplyDelete
  91. Hi.
    You post was really helpful.
    I was wondering if there is a way to make requests in JSON an receive a more meaningful JSON response?

    ReplyDelete
  92. Hai TejPrakash,

    Can you please send me a sample code that works as follows..
    At client side use android and get a current location coordinates latitude and longitude...then send those coordinates to server side(Asp.net,mvc) and server use those coordinates and display location on on map.

    ReplyDelete
  93. Hello tej,
    I've query about GCM Notification.
    As per your above article, I've done everything I'm getting Outpput as
    id=0:1458643592526164%70628bd466d6cf16

    But Notification is not Received over Mobile.

    Please help me out with this solution.

    Thanks in advance.

    ReplyDelete
    Replies
    1. Hi,
      Make sure that your GCM Intent activity code is correct in your Android application.
      In OnMessage method, you should use same parameter that you use in server side. e.g:message.
      String receivedata = intent.getStringExtra("message");

      Please check it.

      Delete
    2. Hi Tej,
      You were right. I was passing wrong JSON string to Mobile App.
      Now it is working Fine.

      Thanks For you immediate reply and Help.

      Thanks again.

      Delete
  94. Hi Tej,
    As GCM now support to send notification to both Ios and Android app
    Can I send notification to both Ios and Android app by this code?

    ReplyDelete
  95. Hi,

    Nice article.
    Please send me .sln file in email.
    My Email id is sunilkmr284@gmail.com.

    ReplyDelete
  96. Plz share the code for image sent.

    ReplyDelete
  97. 'SENDER_ID'
    what is SENDER_ID in your code and how we access this?

    ReplyDelete