failed to using google GCM in android and .NET

222 views Asked by At

I try to use GCM in my asp.net and android project.

it takes about 3days and nothing change.

what's wrong with my codes? I'm really confused...

android side: onCreate

 static final String GOOGLE_SENDER_ID = "tokyo-hghgf93712";  

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_register);

            final String regIde = GCMRegistrar.getRegistrationId(this);
            if (regIde.equals("")) {
                GCMRegistrar.register(this, GOOGLE_SENDER_ID);
                Log.v(regIde, "Done!");
            } else {
                Log.v(regIde, "Already registered");
            }
    .....

asp.net many of my function

function 1:

 public void SendCommandToPhone(String sCommand)
{
    String DeviceID = ";

     // DeviceID = "THE DEVICE ID YOU ARE SENDING TO";

WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "tokyo-hghgf93712"));

String collaspeKey = Guid.NewGuid().ToString("n");
//String postData=string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, "Pickup Message", collaspeKey);
String postData = string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, sCommand, collaspeKey);

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();

tReader.Close();
dataStream.Close();
tResponse.Close();

}

function 2:

protected void Page_Load(object sender, EventArgs e)
          {
              if (IsPostBack)
              {
                  string BrowserAPIKey = "AIzaSygfdgdfgdfgfdgdfpjxgcw";

                  string message = "monaaaaaaa";
                  string tickerText = "test";
                  string contentTitle = "title";
                  string postData = "{ \"registration_ids\": [ \"" + tbRegistrationID.Text + "\" ], \"data\": {\"tickerText\":\"" + tickerText + "\", \"contentTitle\":\"" + contentTitle + "\", \"message\": \"" + message + "\"}}";

                  string response = SendGCMNotification(BrowserAPIKey, postData);

                  litResult.Text = response;
              }
          }


          /// <summary>
          /// Send a Google Cloud Message. Uses the GCM service and your provided api key.
          /// </summary>
          /// <param name="apiKey"></param>
          /// <param name="postData"></param>
          /// <param name="postDataContentType"></param>
          /// <returns>The response string from the google servers</returns>
          private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
          {
              // from here:
              // http://stackoverflow.com/questions/11431261/unauthorized-when-calling-google-gcm
              //
              // original:
              // http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP

              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;
              // Request.Headers.Add(string.Format("Sender: id={0}", "5637737476457"));
              //  Request.Headers.Add(string.Format("Authorization: key={0}", "5637737476457"));

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


          public static bool ValidateServerCertificate(
                                                    object sender,
                                                    X509Certificate certificate,
                                                    X509Chain chain,
                                                    SslPolicyErrors sslPolicyErrors)
          {
              return true;


 }

function 3:

 public void SendNotification(string data)
          {

              string RegId =
                  ";
                  string ApplicationID = "AIzaSygfdgdfgdfgfdgdfpjxgcw";
                  string SENDER_ID = "5637737476457";
              var value = "Lokesh"; //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 the 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  
              //label_Result.Text = sResponseFromServer; //Assigning GCM response to Label text
              tReader.Close(); dataStream.Close();
              tResponse.Close();
          }
0

There are 0 answers