2017-04-05 103 views
4

我试图将我的服务器上的通知发送到我的Android设备。我正在使用Firebase Cloud Messaging发送通知。我可以通过Firebase控制台发送通知,并在手机上收到该消息。但是,我试图通过我的服务器发送一条消息,该服务器还没有工作。FCM HTTP请求返回message_id,但在Android上没有收到消息

我得到如下回应当我执行下面的代码:

“{\” MESSAGE_ID \ “:58934758934758936346437}”

当我们考虑的火力地堡权的文档在这里Firebase Documentation,我们可以看到接收message_id意味着消息已经成功发送。尽管我的手机没有收到。

我没有订阅应用程序到正确的话题。

我运行下面的代码:

private void test(String topic) { 
    try { 
     //Setup request 
     URL url = new URL("https://fcm.googleapis.com/fcm/send"); 
     HttpURLConnection hc = (HttpURLConnection) url.openConnection(); 
     hc.setDoOutput(true); 
     hc.setDoInput(true); 

     //Set request params 
     String message = "{\"to\": \"/topics/" + topic + "\"}"; 

     hc.addRequestProperty("Content-Type", "application/json"); 
     hc.addRequestProperty("Authorization", "key=SECRET"); 

     DataOutputStream dos = new DataOutputStream(hc.getOutputStream()); 
     dos.writeBytes(message); 
     dos.close(); 

     //Get Response 
     InputStream is = hc.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+ 
     String line; 
     while ((line = rd.readLine()) != null) { 
      response.append(line); 
     } 
     rd.close(); 

     label.setText("RESPONSE: " + response.toString()); 

    } catch (Exception ex) { 
     label.setText("Er ging iets mis"); 
     ex.printStackTrace(); 
    } 
} 

回答

4

检查从服务器发送的报文格式。

例如,这里是在相同的IM应用如上的JSON格式消息,所述信息被封装在数据密钥和客户端应用程序预期解释内容:

{ 
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", 
    "data" : { 
    "Nick" : "Mario", 
    "body" : "great match!", 
    "Room" : "PortugalVSDenmark" 
    }, 
} 

对于更多疑问,请查看本文档: FCM Docs

+0

工程就像一个魅力,谢谢! – Guido

+1

很高兴它帮助你!快乐编码! –

3

你有效载荷不包含任何消息

String message = "{\"to\": \"/topics/" + topic + "\"}"; 

它只包含收件人(to),但没有实际的消息。发送notificationdata消息有效负载。事情是这样的:

String message = "{\"to\": \"/topics/" + topic + "\", 
    \"notification\" : { 
     \"title\" : \"sample title\", 
     \"body\" : \"sample body\" 
    } 
}"; 

了解可用的参数notificationdatahere,请注意这两个消息负载的处理方式不同。有关更多详细信息,请参见Receiving Messages in Android文档。