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
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRGKtmaECl8zCiVCDGPgW2yEeTvGnO7_XmttRfrtolFkS0XKns22D95NSuXxBnoo_xS0c24Bpkf3Q9R37Em_BJbQt20lN-A9CzP07EHxNDUixzkBTlre43EOHEVB_0ZUNi5I7lf9pHw8M/s320/PushMain.png)
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
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.
receiving the message. It must contain at least 1 and at
most 1000 registration IDs. To send a multicast message,
you must use JSON.
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="
"collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" +
regId + "";
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.....
Enjoy coding.....
It helped me a lot. thanks..
ReplyDeleteHi could you provide me with the actual .sln package.
ReplyDeleteSend me your mail-ID.
DeleteAppreciate your generosity on this knowledge, nice if you would youtube this tutorial.
ReplyDeleteHi Tej,
ReplyDeletecan you tell what is the difference of using WCF instead of ASP Web Application? And what is the most suitable method? Thanks.
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.
Deletestarun88@gmail.com
Delete
ReplyDeletehi 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.
Hi mani,
DeleteYou 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
Hi Tej,
ReplyDeleteThank 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.
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.
Deletethanks......
Hi Tej,
ReplyDeleteThanks for your wonderful article.
Can you send me your actual solution?
My mailid -> rajibmvp@gmail.com
Hi Tej , Can you plz give me .sln project ?
ReplyDeleteMy Email Id : nikunj.ce31@gmail.com
ReplyDeleteDownload from here: https://www.dropbox.com/s/cs7ibm7q1ir20gy/AndroidPushNotifications.zip
DeleteI really need it. you can update link?. it's die! thanks you.
Deletethis is my email, or you can send link download project AndroidPushNotifications.zip for me. hjhj
Deletenaquoc1204@gmail.com
DeleteHello Tej....can you please give me the database script fot this project ???
ReplyDeleteHi Niks,
DeleteCreate 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.
Hi Tej,
ReplyDeleteI am getting the below error The remote name could not be resolved: 'android.googleapis.com'.
can u pls advise on this.
Hi Easwaran,
DeleteYour sending bad request or incorrect data to the server.Please check your URL format and data that your sending to server.
I had the same error, but in the server I had a bad DNS ip, the entire server doesn't had internet.
DeleteHi Tej,
ReplyDeletebelow 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() + "®istration_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();
}
Hi Easwaran,
DeletePlease 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.
Thanks Tej
ReplyDeleteis 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.
Yes, it is mandatory.
Deletethat'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.
how can i send notification to multiple users? how should i use registratiomids? in which format?
ReplyDeleteHi hetal,
DeleteYou 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.
Hi tej, can you plis give an example how to arrange the IDs in JSON format? thank you so much.
DeleteHow can i know automatically that my blog or site is changed and if it has change then push notification send to device..?
ReplyDeleteHi Pratik,
DeleteYou 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.
Hi I am using the steps you mentioned above and notification sent successfully but the message is not appearing.
DeleteHi manish,
DeleteMake 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");
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
ReplyDeleteHi Sumant,
DeleteI 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
Thank you!! It is working fine!!
ReplyDeleteIs it possible to send the message to multiple devices using the same WebRequest?
Yes, it is possible to send multiple message.
ReplyDeletetRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
ReplyDeletetRequest.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?
Exception 401 means an error authenticating the sender account. Posting data format to GCM Server is wrong. please check the above tutorial once.
DeleteI 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
DeleteI deleted the double brackets {{-}} and replaced for single ones {-} and deleted all space in the json string. Now is working ok. Thank you!
DeleteI 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.
DeleteI added these lines to the manifest:
Hi Pixue,
Deleten 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.
It is working again, I had a problem in the manifest file. Thank you!!
DeleteThis comment has been removed by the author.
ReplyDeleteString receivedata = intent.getStringExtra("message");
ReplyDeleteGetting null data plz help
Make sure that server side & client side should be same named parameters. Ex:message.
Deletenot able to download code from the given link.pls send it to my mail id sathyacsermd@gmail.com
ReplyDeleteHi sathya,
Deletetry this......https://app.box.com/s/01ipxjbs7d24b3et6vvw
Hi Tej,
Deletei 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
Hi Sathya,
DeleteYes, you have to give same URL.
could u tell me why socket exception is occuring?
Deletegetting unable to connect to the server
Deletein this line Stream dataStream = tRequest.GetRequestStream();
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.
Deleteyes Tej,i tryed with the same code.
Deletei changed only the sender id,app id,reg id.
same exception throwing..any idea?
hi Tej,
Deletenow 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.
Hi Tej,
ReplyDeleteeven 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.
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.
ReplyDeleteHi danish,
DeleteFollow 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.
unable to send multiple devices.Can you please post some sample code
ReplyDeleteHi rams,
DeleteYou can kept upto 1000 regID's in Json format or you can loop the code.
I am unable to send multiple devices.Can you please post some sample code.
ReplyDeleteplease 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() + "®istration_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();
by passing json data I am getting invalid registration id error.
ReplyDeleteHi Tej,
ReplyDeleteI 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).
Yes, I have done for IOS using Moon-apn s. Simply you can loop the code for multiple.
DeleteHello ,
ReplyDeleteWhen 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
Hi Meghal,
DeleteYour sender Id or Registration Id may be wrong. Send valid ID's to GCM server.
Hello Tej ,
DeleteBut 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.
hi..
ReplyDeleteCan 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
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.
DeleteHi,
ReplyDeleteIm 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?
This is the stored_procedure to get the table content
DeleteCREATE PROCEDURE [dbo].[Proc_PushGetRegId]
AS
BEGIN
Select RegID from AndroidRegId
END
Hi Kow, On which base, your retrieving the regID?
DeleteFor example, I am retrieving RegID for particular USER (below query).
Select RegID from AndroidRegId where UserID=@userid
I wanted to try retrieve the 1st content from the table.
Deletehow your are saving records in DB?
DeleteThis comment has been removed by the author.
ReplyDeleteI 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!
ReplyDeletestring regId = dsregID.Tables[0].Rows[0]["RegID"].ToString();
Tej can you please tell ,me how to send registration id that i recieved from GCM server to my local .net server?
ReplyDeleteHi 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.
DeleteIn your server utilities class i send reg id to a method like this
Deletepublic 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 .
where as PostRegistrationId is the method name of my webservice that i want to invoke.
DeleteFor 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''.
Deleteok thanx :)
Deletehi 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
DeleteUse 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.
DeleteHelloo Tej please is there and php version for the server side code ? Thanks in advance
ReplyDeleteHi Ali, I don't have php version. But you can find php side code easily on google search.
DeleteHai Tej ,Please help me , i am getting error as (The remote server returned an error: (401) Unauthorized.) what i did mistake?
ReplyDeleteprotected 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() + "®istration_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();
}
Hi sateesh, exception 401 means an error authenticating the sender account. You may sending wrong regID, appID or senderID to the server. Check once.
DeleteThanks Tej Prakash i solved that but i got one more error as (Error=MismatchSenderId) How to solve this?
DeleteWhat you sending the RegID to GCM server is not registered with your SENDERID. So that you are getting MISMATCHED ERROR.
DeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
Delete1. It's easy to arrange in Json string. You can send up-to 1000 Regid's to GCM server once like {1,2,3......}.
Delete2. You have to provide USERID to get specific user RegId.
This comment has been removed by the author.
Deletehi Tej, am getting unauthorized (401) in WebResponse tResponse = tRequest.GetResponse(); line
DeleteI tried a lot and still get error " The remote server returned an error: (401) Unauthorized. "
ReplyDeleteI'm sure tha applicationID (Key for browser applications), SENDER_ID (Project Number), and regId is correct.
Error in line WebResponse tResponse = tRequest.GetResponse();
Hi Tej,
ReplyDeleteIn the status bar, How can we show the message count when there are multiple message at the same time?
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
DeleteSir 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
ReplyDeleteThanks
Hi Fiaz, get the record based on User-Id. And send to particular user.
DeleteHi 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
ReplyDeletevenu3699@gmail.com my id
DeleteHi 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
DeleteHi 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.
DeleteThanks in advance
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.
DeleteHi Tej, I tried it again now I am getting Error=InvalidRegistration in the place of GCM server responce? what wrong I am doing?
ReplyDeleteanyway I got finally thank you tej
ReplyDeletehmm!! good.
DeleteHi 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
ReplyDeletethanks in advance
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"}.
Deletewhere I can find Registration Id, how?
ReplyDeleteHi Master, your Android mobile receives the RegistrationID from Google.
DeleteFor more info visit: http://www.tejaprakash.com/2013/02/google-cloud-messaging-for-android.html
Hi Tej,
ReplyDeleteCan you give sample code for sending push notifications to multiple registered ids at a time by clicking a button....
Hi Tej,
ReplyDeleteI 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
Hi Tej,
ReplyDeleteI 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
Pls anyone solve my problem
ReplyDeleteHi,
ReplyDeleteI 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.
Hi could you provide me with the actual .sln package.
ReplyDeletemy mail id is haiajster@gmail.com
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
ReplyDeleteHi I am getting an error at this point
ReplyDeleteWebResponse tResponse = tRequest.GetResponse();
The remote server returned an error 401: Unauthorized
Hello Tej Prakash Rao Peddineni Sir,
ReplyDeletePlease 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
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.
ReplyDeleteHi Tej, Many many thanks for very helpful artical but could you please add how can I send notification to multiple devices in 1 requrest?
ReplyDeleteHi Tej, I got my answer http://stackoverflow.com/questions/22486192/gcm-error-missingregistration-sending-messages-via-json
Deletewhere to get RegistrationID??? still not sure
ReplyDeletehow to implement deepl linking with this code
ReplyDeleteHi tej, Please send db script of the app. Thank You
ReplyDeleteSir 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
ReplyDeleteHi, 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.
ReplyDeleteCheck Out
ReplyDeletehttp://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)
Thanks. This helped a lot.
ReplyDeleteHow to send image via push notification using c#
ReplyDeleteHi sujith,
DeleteThere 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"
}
hi tej,
ReplyDeletePlease send db script of this app
i need stored procedure and database table..field
my mail id is elaunch.pankaj@gmail.com
please, send stored procedure code
DeleteWebResponse tResponse = tRequest.GetResponse();
ReplyDeleteGive Error :=> The remote server returned an error: (401) Unauthorized.
Hi Sumit,
DeleteMake sure that google api key and senderID are correct.
Notification recieved on my android device is blank only with app icon and its name,not displaying message ..tried with json data format too.
ReplyDeleteHi Ansari,
DeleteMake 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.
Hello Tej.
ReplyDeleteI 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.
Hi Akhilesh,
DeleteYou 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
You mean that registrationID from my app.
DeleteI 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.
ReplyDeleteYes, you to need get it from app. But I don't know about the registration before the creation of app.
DeleteDear Tej
ReplyDeleteI have got Registration id which is something like "APA91bGKRMzGGrE8YWfLVBs9juTsGnzCtAjaqvgwdVMRDn3HQleGRNdsZfUwDSJWdYpHbyASox4PqvEfE40GcKq516D2by1ImIHsxb2YzksvYkPh5zgU76cqZb_Orx-XxA8QNd3bpwGR" but when i was sending notification is produced Error MismatchSenderid
Hi Akhliesh,
DeleteThat's an valid registration ID but check your senderID (i.e ProjectID in google console) is correct or not.
let me check and will tell you, thanks tej for helping me.
Deletehello Tej,
ReplyDeleteI am getting error on this line :
Stream dataStream = tRequest.GetRequestStream();
Error:
This stream does not support seek operations.
hello tej
ReplyDeletethanq
it help me a lot
Hello Tej
ReplyDeletehow can we create server for sending push notification in c#
I didn't get you what you mean. But you can use a windows service or schedule jobs in server.
DeleteHi tej
ReplyDeleteAppName(Title) not showing ...i am using same code. pls help
hello frnd i get the error when i click on button
ReplyDeleteerror...."error=MismatchSenderId"
Hi Piyush,
DeletePlease check your Sender Id and RegID. Sometimes RegID may expires.
ohk will let u know after check regid ..thankzz for yr reply...
Deletedone tej prakash rao....there is an reg id prblem only..thankzzz
Deletehello sir me develope app in this information come to db its developed in .net webservice file and software also in .net
ReplyDeletei 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
Hi,
DeleteWrite 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.
can i talk u on call sir plzz
ReplyDeleteSure! Reach me at tejaprakashp@gmail.com
Deletehelloo 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?
ReplyDeletehello tej prakash rao what is your server_url for android application for GCM notification ?
ReplyDeleteHi, You need place your Web_service URL there.
DeleteThanks 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?
ReplyDeleteHi 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.
DeleteHi, I am receiving 'null' text. plz help.
ReplyDeleteHi, I am receiving 'null' text. plz help.
ReplyDeleteHi Shah,
DeleteMake sure that server side & client side should be same named parameter. Ex:message.
hello tej how are you.
ReplyDeletethe 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
and please tell me how can we write server code for sending notifications
ReplyDeletehello tej i am getting error MismatchSenderid
ReplyDeleteHi 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).
ReplyDeleteBut my question is, do i need a ssl certificate in my webserver to use this code?.
Thanks.
Hi, SSL certificate is not required to send notifications.
DeleteThis comment has been removed by the author.
DeleteI tried again after check the code (i use VB .Net ) and works!! Thanks Tej!
DeleteBro I am getting this exception ==>
ReplyDeleteSystem.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()
Como relaciono mi Android con la aplicacion que enviara el mensaje
ReplyDeleteHello,
ReplyDeleteHow can I send image in push notification to android using asp.net and c#.
Hi Samir,
DeleteThere 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"
}
Hai. I'm getting below Error
ReplyDelete"The remote server returned an error: (401) Unauthorized."
i cannot understand why the above code gives socket exceptions when hosted on a web site panel . but it works fine on localhost.
ReplyDeletehi
ReplyDeletehow i get GCM registration Id
How to send telugu unicode notifications using this ? while sending telugu unicode text, its showing empty data.
ReplyDeleteHi Lokesh,
DeleteEncode 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.
Can you please send me a sample for encoding and decoding
DeleteI tried so many ways but i'm unable to get the telugu messages/notifications.
DeleteOk any way. Thank you
Hi,
ReplyDeleteHow to push multiline message . Please help
which db i have to use. or please send me sql script on my mail id mani007tiwari@yahoo.in
ReplyDeletehow we can get android app. which need to be installed.i have created my project and got key but i didnt get res id .
ReplyDeleteHi.
ReplyDeleteYou post was really helpful.
I was wondering if there is a way to make requests in JSON an receive a more meaningful JSON response?
Hai TejPrakash,
ReplyDeleteCan 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.
Hello tej,
ReplyDeleteI'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.
Hi,
DeleteMake 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.
Hi Tej,
DeleteYou 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.
Hi Tej,
ReplyDeleteAs 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?
Hi,
ReplyDeleteNice article.
Please send me .sln file in email.
My Email id is sunilkmr284@gmail.com.
Plz share the code for image sent.
ReplyDelete'SENDER_ID'
ReplyDeletewhat is SENDER_ID in your code and how we access this?