在我的项目中,我需要从服务器向客户端发送通知。我能够从FCM控制台发送通知,但是当我从服务器向客户端发送通知时, remoteMessage.getNotification()始终返回null。正确接收数据时。当我同时发送数据和通知时,通知为null时,仅数据为非null。
我已经检查了this问题。但是该解决方案不适用于我。
下面是调试客户端应用程序时的客户端和服务器端代码片段以及屏幕截图。
客户端应用:(onMessage已接收)
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
Log.e(TAG, "From: " + remoteMessage?.from)
// Check if message contains a data payload.
if ((remoteMessage?.data?.size ?: 0) > 0) {
Log.e(TAG, "Message data payload: ${remoteMessage?.data}")
}
val a = remoteMessage?.notification
if (a != null) {
Log.e(TAG, "Message Notification Body: " + remoteMessage.notification?.body)
}
}
服务器端代码(node.js)
var request = require('request');
// Set the headers
var headers = {
'Content-Type':'application/json',
'Authorization': 'key=AIzaSyAzMLMp....'
}
// Configure the request
var options = {
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: headers,
form: {
"to": "eZoeSIRba6g:AP...",
"notification" : { "body" : "my body"} }
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
console.log(body + " error : " + error)
})
如果我使用以下部分,则代码可以正常工作。
form: {
"to": "eZoeSIRba6g:APA91bEYrP...",
"data" : { "body" : "my body"} }
调试应用程序时的屏幕截图(检查变量“a”的值)
如果有人对如何解决此问题有任何想法,请帮助我。
先感谢您。
最佳答案
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
}
使用这样的JSON,然后将调用onMessageReceived。