设备无法获得推送通知

时间:2014-01-29 10:11:04

标签: android push-notification google-cloud-messaging

我尝试在android中编写push notifcation应用程序我使用来自此http://developer.android.com/google/gcm/client.html的客户端代码,我的服务器在C#中我使用Http,当我发送消息时它返回状态OK(200)和字符串,

like:{"multicast_id":32662462384623626,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:436476385463457%ceb6237df9fd7ecd"}]}
I tryed to use in emulator google API 18 and in my device with Android 2.2 but both didn't get push notification. 

API_KEY = from Public API access-> API Key;
DEVICE_ID = app gets it as wrote in documentation  regid = gcm.register(SENDER_ID);

服务器代码:

public string GsmRequest(string postData)
    {
        var request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        request.ContentType = " application/json";
        request.Method = "POST";
        request.KeepAlive = false;        
        //request.Headers.Add(string.Format("Authorization: key={0} {1}", API_KEY,GetSimpleJSON(DEVICE_ID)));

        request.Headers.Add(string.Format("Authorization: key={0}", API_KEY));
        using (var sw = new StreamWriter(request.GetRequestStream()))
        {
            var json = GetSimpleJSON(DEVICE_ID);
            sw.Write(json);
            sw.Flush();
            sw.Close();
        }

        try
        {
            var response = request.GetResponse();
            var responceCode = ((HttpWebResponse) response).StatusCode;
            if (responceCode.Equals(HttpStatusCode.Unauthorized) ||
                responceCode.Equals(HttpStatusCode.Forbidden))
            {
                var text = "Unauthorized - need new token";
            } else if (responceCode.Equals(HttpStatusCode.OK) == false)
            {
                var text = "Response from web service isn't OK";        
            }

            var reader = new StreamReader(response.GetResponseStream());
            var responceLine = reader.ReadToEnd();
            reader.Close();

            return responceLine;
        }
        catch (Exception e)
        {
            return "error: "+e.ToString();
        }
    }


   public string GetSimpleJSON(string text)
    {
        return "{\"data\": { \"message\" : " + "\"" + "true" + "\"}, \"registration_ids\":[\"" + text + "\"]}";
    }

0 个答案:

没有答案