gcm onMessage()被调用,但数据为空...?

时间:2013-01-02 09:59:48

标签: android asp.net google-cloud-messaging

我正在使用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服务时,它在调试中调用正确,但这里消息字符串变为空。

任何人都可以帮忙,我哪里出错...

3 个答案:

答案 0 :(得分:1)

您的邮件应使用以下参数发布:

'registration_ids' => DeviceID ,
'data' => array( "notification" => YOUR_JSON_MESSAGE_STRING),

在android方面,:

Bundle data = intent.getExtras();
data.getString("notification")

答案 1 :(得分:0)

在应用程序中尝试此操作

@Override
protected void onMessage(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String message = extras.getString("message");
}

答案 2 :(得分:0)

可能的原因是参数所需的“消息”与服务器中定义的不完全相同。

您的密码:

@Override
protected void onMessage(Context context, Intent intent) {
     String message = intent.getStringExtra("message");
}

但在服务器中,例如PHP服务器:

$msg = array("mess" => "Hellow World!");
sendNotif($msg);

请参阅PHP文件中的mess!=消息,除非您将代码更改为

,否则很可能会返回null
 @Override  
 protected void onMessage(Context context, Intent intent) {
      String message = intent.getStringExtra("mess");
 }