FCM云功能,用于服务器无推送通知安卓



我需要一个例子来提供Firebase云功能,用于Android的服务器无推送通知。

在Android端输入此代码,您希望在其中触发云函数以发送通知,例如。 在聊天应用程序中发送消息时:

Message message =
            new Message(timestamp, -timestamp, dayTimestamp, body, ownerUid, userUid);
    mDatabase
            .child("notifications")
            .child("messages")
            .push()
            .setValue(message);
    mDatabase
            .child("messages")
            .child(userUid)
            .child(ownerUid)
            .push()
            .setValue(message);
    if (!userUid.equals(ownerUid)) {
        mDatabase
                .child("messages")
                .child(ownerUid)
                .child(userUid)
                .push()
                .setValue(message);
    }

在您初始化Firebase Cloud Functions的目录中,该代码在Android应用中发送消息时触发:

exports.sendNotification = functions.database.ref('/notifications/messages/{pushId}')
.onWrite(event => {
    const message = event.data.current.val();
    const senderUid = message.from;
    const receiverUid = message.to;
    const promises = [];
    if (senderUid == receiverUid) {
        //if sender is receiver, don't send notification
        promises.push(event.data.current.ref.remove());
        return Promise.all(promises);
    }
    const getInstanceIdPromise = admin.database().ref(`/users/${receiverUid}/instanceId`).once('value');
    const getReceiverUidPromise = admin.auth().getUser(receiverUid);
    return Promise.all([getInstanceIdPromise, getReceiverUidPromise]).then(results => {
        const instanceId = results[0].val();
        const receiver = results[1];
        console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);
        const payload = {
            notification: {
                title: receiver.displayName,
                body: message.body,
                icon: receiver.photoURL
            }
        };
        admin.messaging().sendToDevice(instanceId, payload)
            .then(function (response) {
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });
    });
});

有关更多信息,请查看此内容 - 使用适用于 Firebase 的云函数的无服务器通知

最新更新