繁体   English   中英

Android通知使用GCM和带有JSON消息的Java推送为空

[英]Android notification push empty using GCM and java with json message

我正在努力将通知推送到Android设备。

这是我编写的一小段代码:

    String API_KEY = "AIzaSy....";
    String url = "https://android.googleapis.com/gcm/send";
    String to = "ce0kUrW...";

    String data = "{\"to\": \"" + to + "\"}";

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), data);

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).post(body).addHeader("Authorization", "key=" + API_KEY).build();

    Response response = client.newCall(request).execute();
    System.out.println(response.headers());
    System.out.println(response.body().string());

查看https://developers.google.com/cloud-messaging/http#send-to-sync ,当我尝试使用send-to-sync选项时,效果很好。 我在手机上收到通知声音,但没有实际通知,因为没有消息或数据链接到推送。

现在,当我用以下行替换数据字符串时,仍然得到相同的结果:

    String data = "{ \"notification\": {\"title\": \"Test title\", \"text\": \"Hi, this is a test\"},\"to\" : \""
    + to + "\"}";

我不确定我缺少什么。 我的猜测是我的通知格式有误,但是我尝试了到目前为止在研究过程中发现的所有组合。

他们将日志写入如下:

内容类型:application / json; 字符集= UTF-8

日期:2016年4月21日,星期四10:51:23 GMT

过期:星期四,2016年4月21日10:51:23 GMT

缓存控制:私有,最大年龄= 0

X-Content-Type-Options:nosniff

X-Frame-Options:SAMEORIGIN

X-XSS-Protection:1; 模式=阻止

服务器:GSE

备用协议:443:quic

Alt-Svc:quic =“:443”; ma = 2592000; v =“ 32,31,30,29,28,27,26,25”

传输编码:分块

OkHttp所选协议:http / 1.1

OkHttp发送Millis:1461235877551

OkHttp收到的Millis:1461235877855

{“ multicast_id”:6596853786874127657,“ success”:1,“ failure”:0,“ canonical_ids”:0,“ results”:[{“ message_id”:“ 0:1461235883968556%6ff215a7f9fd7ecd”}]}

日志条目指示您的消息已成功处理。 但是,对于带有有效负载选项的通知,您应该发送这样的JSON消息:

{
    "to" : "<your-recipient-id>",
    "notification" : {
      "body" : "Hi, this is a test",
      "title" : "My test"
    }
  }

请按照建议进行更改,并告诉我们是否有帮助。 您可以查看《开发人员指南》中的“ 消息传递概念和选项” ,该指南提供了一些有用的示例。

也许举个例子-这就是您处理通知的方式。 在应用程序的onMessageReceived()您可以通过将notification作为键来检索通知有效负载,从而对其进行处理。 例如:

public void onMessageReceived(String from, Bundle data) {
     String notificationJSONString = data.getString("notification");
     //then you can parse the notificationJSONString into a JSON object
     JSONObject notificationJSON = new JSONObject(notificationJSONString ); 
     String body = notificationJSON.getString("body");
     Log.d(TAG, "Notification Message is : " + body);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM