![](/img/trans.png)
[英]Android GCM Java Server - Push Notification without message data
[英]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.