以下是您可以实现此目的的方法:
第1步:
???在firebase上创建项目并生成服务器密钥.
第2步:
为fcm服务器生成json对象.这里的消息可能包含数据对象和通知对象.它还必须有接收器fcm id.样本json就像:
{
"notification":
{
"notificationType":"Test",
"title":"Title ",
"body":"Here is body"
},
"data":
{"notificationType":"Test",
"title":"Title ",
"body":"Here is body"
},
"to":"dlDQC5OPTbo:APA91bH8A6VuJ1Wl4TCOD1mKT0kcBr2bDZ-X8qdhpBfQNcXZWlFJuBMrQiKL3MGjdY6RbMNCw0NV1UmbU8eooe975vvRmqrvqJvliU54bsiT3pdvGIHypssf7r-4INt17db4KIqW0pbAkhSaIgl1eYjmzIOQxv2NwwwwXg"
}
第3步:
编写一个Rest调用者服务,它将通过以下url与fcm服务器通信:
https://fcm.googleapis.com/fcm/send
以下是示例工作代码:
public class PushNotificationServiceImpl {
private final String FIREBASE_API_URL = "https://fcm.googleapis.com/fcm/send";
private final String FIREBASE_SERVER_KEY = "YOUR_SERVER_KEY";
public void sendPushNotification(List keys, String messageTitle, String message) {
JSONObject msg = new JSONObject();
msg.put("title", messageTitle);
msg.put("body", message);
msg.put("notificationType", "Test");
keys.forEach(key -> {
System.out.println("
Calling fcm Server >>>>>>>");
String response = callToFcmServer(msg, key);
System.out.println("Got response from fcm Server : " + response + "
");
});
}
private String callToFcmServer(JSONObject message, String receiverFcmKey) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Authorization", "key=" + FIREBASE_SERVER_KEY);
httpHeaders.set("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("data", message);
json.put("notification", message);
json.put("to", receiverFcmKey);
System.out.println("Sending :" + json.toString());
HttpEntity httpEntity = new HttpEntity<>(json.toString(), httpHeaders);
return restTemplate.postForObject(FIREBASE_API_URL, httpEntity, String.class);
}
}
你必须只调用sendPushNotification(List< String> receiverKeys,String messageTitle,String message)然后接收器将获得推送消息
谢谢 :)