android - 如何使用 Spring Boot 在 Google Firebase FCM 上推送通知?
问题描述
我正在寻找一种将通知从服务器(Spring Hibernate RESTful API)推送到客户端应用程序的解决方案,用 Angular 和 Android 编码。我想实施一个不会占用太多用户带宽的解决方案,因为我的用户群的连接性有限(低带宽和 3G/2G 移动网络)。这排除了轮询作为一种可能的解决方案。接下来,我研究了套接字连接,但看起来套接字连接可能会保持打开状态并导致内存泄漏问题。接下来,我尝试使用 Google FCM,但仍停留在实施中。具体来说,我试图在 FCM 上发送通知,但没有在客户端接收它。回顾一下,我必须从 JAVA 层(Spring boot)发送通知,并在 Angular 和 Android 上接收它。我尝试了一些示例代码来使用 FCM 完成这项工作。但它不起作用。请向我建议解决方案或使这项工作发挥作用的不同方法。这是我正在使用的代码:
JSONObject body = new JSONObject();
body.put("to", "/users/" + TOPIC);
body.put("priority", "high");
JSONObject notification = new JSONObject();
notification.put("title", "JSA Notification");
notification.put("body", "Happy Message!");
JSONObject data = new JSONObject();
data.put("Key-1", "JSA Data 1");
data.put("Key-2", "JSA Data 2");
body.put("notification", notification);
body.put("data", data);
HttpEntity<String> entity = new HttpEntity<>(body.toString());
RestTemplate restTemplate = new RestTemplate();
ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + FIREBASE_SERVER_KEY));
interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
restTemplate.setInterceptors(interceptors);
String firebaseResponse = restTemplate.postForObject(FIREBASE_API_URL, entity, String.class);
CompletableFuture<String> pushNotification = CompletableFuture.completedFuture(firebaseResponse);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
System.out.println("reponse "+firebaseResponse);
return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
从 firebaseResponse,我在浏览器中得到以下响应:
{"multicast_id":6197426474050349577,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
看来我的消息没有发送。任何示例工作代码将不胜感激。谢谢您的帮助。- 普拉纳夫
解决方案
FIREBASE_SERVER_KEY 错误。如果 FIREBASE_SERVER_KEY 正确,则响应应如下所示。
{"multicast_id":7163645588662808791,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1563534037236589%eec6c0c0eec6c0c0"}]}
推荐阅读
- python - odoo 数据迁移:通过 python 上的 odoorpc 在多个价目表上输入一种产品
- c++ - 如何将模板 T 转换为类指针
- php - 如何在 php 中使用正则表达式验证字符串长度?
- javascript - JQuery 遍历一个表
- r - 在 R Shiny 中使用用户定义函数返回多个我想输出的值
- java - 后备工厂无法处理 Feign 客户端中的自定义异常
- android - android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked 处的 StringIndexOutOfBoundsException
- python-3.x - 此代码中返回的数据类型是什么?如果这是实例,那么我们如何使用此返回值获取值?
- reactjs - 如何在 react-redux 中实现刷新令牌
- java - 如何反序列化包含相同键名但使用不同类型的 JSON 文件(使用 Google JSON)?