我目前正在使用 Flutter 和 Node.js 后端编写一个 Android 应用程序。
在客户端,我按照firebase_messaging 文档的前 3 个步骤将 FCM 集成到我的应用程序中。我的应用程序的逻辑根据不同的设置订阅和取消订阅多个主题(一个用户平均订阅了 12 个主题) 。
服务器逻辑应该根据条件发送各种通知消息:
const firebase = require('firebase-admin')
firebase.initializeApp({
credential: firebase.credential.applicationDefault(),
databaseURL: 'https://<PROJECT>.firebaseio.com'
})
const title = ...
const msgList = [...]
const notifications = []
for (let msg of msgList) {
let condition = `'${msg.topicA}' in topics && '${msg.topicB}' in topics`
if (msg.topicX !== '') {
condition = `${condition} && !('${msg.topicX}' in topics)`
}
notifications.push(buildMessage(title, msg.body, condition))
}
new Promise((resolve, reject) => {
return firebase.messaging().sendAll(notifications).then(resp => {
console.log(`Sent ${resp.successCount} messages, ${resp.failureCount} failed`)
resolve()
})
}).then(() => {
firebase.app().delete()
}).catch(err => {
console.error(err)
})
function buildMessage(title, body, condition) => {
return message = {
notification: { title, body },
android: {
ttl: 24 * 60 * 60 * 1000, // 1d
notification: {
sound: 'default',
vibrate_timings: [
'0s', '0.1s',
]
}
},
condition
}
}
当我运行此代码时,它会记录Sent 72 messages, 0 failed. 因此,我假设消息的发送有效。发送的消息数量和相应的主题以及标题至少每天都会发生变化。根据我的主题订阅,我实际上应该在手机上收到大约 4 个推送通知。但是,我一次只收到一个通知。在我重新安装应用程序并因此使用新令牌再次订阅主题后,我收到了我应该收到的所有消息。然而,几天后,它又变回了原来的行为,每次服务器发送一批消息时,我都会收到一条消息。