Android通过.net网络服务发送推送通知

时间:2012-11-28 12:03:58

标签: java web-services google-cloud-messaging android-ksoap2 android-webservice

我正在使用以下网络服务从Android发送推送通知。当我第一次调用此Web服务时,需要花费很多时间并且Android设备上不会发送推送通知。它只在从Android调用时才会发生。它完美地作为webservice。

[WebMethod]

    public string SendGcm(String serviceKey,String registrationId ,string message) {
        WebClient wc=new WebClient();
        wc.Headers.Add("Authorization", "key=" + serviceKey);
        NameValueCollection nameValues=new NameValueCollection
            {
                {"registration_id", registrationId},
                {"collapse_key", Guid.NewGuid().ToString()},
                {"data.payload", message}
            };

        var resp=wc.UploadValues("https://android.googleapis.com/gcm/send",
                    nameValues);

        var respMessage = Encoding.Default.GetString(resp);
                return respMessage;
    }

1 个答案:

答案 0 :(得分:0)

使用此 - :

 public void MakeNotificationForAndroid(string DeviceToken, string Body, string Sound, string CustomFrom, string CustomeMsg)
        {
            String DeviceID = "";

            DeviceID = DeviceToken;
            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}", "AIzaSyBX1gD47uiVp0W_UjNxhwtVsQCNJYfg5vI"));

            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.message={1}&collapse_key={2}&data.sound={3}&data.type={4}", DeviceID, Body, collaspeKey, Sound, CustomeMsg);

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