更新时间:2023-02-26 21:27:18
以下是实现此目的的方法:
Here is the way that you can achieve this:
第1步:
在firebase上创建项目并生成服务器密钥。
Step 1: Create project on firebase and generate server key.
步骤2 :
为fcm服务器生成一个json对象。这里的消息可能包含数据对象和通知对象。它还必须有接收器fcm id。示例json类似于:
Step 2: Generate a json object for fcm server. Here message may contains data object and notification object. It must also have receiver fcm id. Sample json is like:
{
"notification":
{
"notificationType":"Test",
"title":"Title ",
"body":"Here is body"
},
"data":
{"notificationType":"Test",
"title":"Title ",
"body":"Here is body"
},
"to":"dlDQC5OPTbo:APA91bH8A6VuJ1Wl4TCOD1mKT0kcBr2bDZ-X8qdhpBfQNcXZWlFJuBMrQiKL3MGjdY6RbMNCw0NV1UmbU8eooe975vvRmqrvqJvliU54bsiT3pdvGIHypssf7r-4INt17db4KIqW0pbAkhSaIgl1eYjmzIOQxv2NwwwwXg"
}
第3步强>:
写下一个将通过以下网址与fcm服务器通信的其他来电服务:
Step 3 : Write a Rest caller service that will communicate with fcm server by following url:
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<String> 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("\nCalling fcm Server >>>>>>>");
String response = callToFcmServer(msg, key);
System.out.println("Got response from fcm Server : " + response + "\n\n");
});
}
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<String> httpEntity = new HttpEntity<>(json.toString(), httpHeaders);
return restTemplate.postForObject(FIREBASE_API_URL, httpEntity, String.class);
}
}
您只需致电 sendPushNotification(List< String> receiverKeys,String messageTitle,String message)
然后接收者将获得推送消息
You have to just call sendPushNotification(List<String> receiverKeys, String messageTitle, String message)
then receiver will get push message
谢谢:)