首页 > 解决方案 > 如何使用 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"}]}

看来我的消息没有发送。任何示例工作代码将不胜感激。谢谢您的帮助。- 普拉纳夫

标签: androidangularspring-bootfirebase-cloud-messaginggoogle-cloud-messaging

解决方案


FIREBASE_SERVER_KEY 错误。如果 FIREBASE_SERVER_KEY 正确,则响应应如下所示。

{"multicast_id":7163645588662808791,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1563534037236589%eec6c0c0eec6c0c0"}]}

推荐阅读