I'm new to all Android GCM push notifications and I have read stack posts but couldn't get a straight answer.I have also read Create push notification in android to get a better understanding of how GCM works. I have also used the gcm-demo-server and gcm-demo-client provided by the SDK. However, here are my doubts and what I have tried so far:
- Regarding the link I have put, the phone which has the app registers to get the registration key. Is this a unique key for all phones which uses the same app?
- Does this registration key expires in any case? (E.g. App running on background)
Assuming that I have the registration key, I have tried the following code snippet to push notification via GCM to my app. This is written on c# .net. Please let me know whether what I have mentioned above can be achieved using the following code snippet:
private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json") { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate); // MESSAGE CONTENT byte[] byteArray = Encoding.UTF8.GetBytes(postData); // CREATE REQUEST HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send"); Request.Method = "POST"; Request.KeepAlive = false; Request.ContentType = postDataContentType; Request.Headers.Add(string.Format("Authorization: key={0}", apiKey)); Request.ContentLength = byteArray.Length; Stream dataStream = Request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); // SEND MESSAGE try { WebResponse Response = Request.GetResponse(); HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode; if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden)) { var text = "Unauthorized - need new token"; } else if (!ResponseCode.Equals(HttpStatusCode.OK)) { var text = "Response from web service isn't OK"; } StreamReader Reader = new StreamReader(Response.GetResponseStream()); string responseLine = Reader.ReadToEnd(); Reader.Close(); return responseLine; } catch (Exception e) { } return "error"; }
Is there a direct way of sending push notifications without the phone first being registered in our custom server?