我在 android 中使用 GCM,我通过 asp.net 服务器将数据发送到设备,如下代码所示。
public void SendCommandToPhone(String sCommand)
{
String DeviceID = "";
DeviceID = "APA91bF9SSDEp-UPU8UwvctGt5ogfrSw0UdilTWlCujqItHcr-eiPJ31ZDI-IeqTbLr92ZOPF31bXtB1_5gNEPHAq82N4ji0stm4cy9U0Yuk0Awhjl9PS02okuc9rRhJobkgOt-ofm5Br0KR-Y";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
//tRequest.ContentType = "application/json";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIzaSyBgCKDhyHnRmmu8jCfmupHVJA8cVkIa-XEZS"));
String collaspeKey = Guid.NewGuid().ToString("n");
String postData = string.Format("registration_id={0}&data.message={1}&collapse_key={2}", DeviceID, "YourMessage", 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();
}
并在应用程序 onMessage 代码如下
@Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getStringExtra("message");
}
当我调用 asp.net 服务时,它在调试中正确调用,但这里的消息字符串为空。
任何人都可以帮忙,我哪里出错了......