用于服务器的FCM云功能少推送通知android

时间:2017-06-21 11:00:42

标签: android firebase push-notification firebase-cloud-messaging google-cloud-functions

我需要一个firebase云功能的示例,用于Android的服务器少推送通知。

1 个答案:

答案 0 :(得分:2)

在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云功能的目录中,该代码会在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);
            });
    });
});

有关详细信息,请查看此内容 - Serverless notifications with Cloud Functions for Firebase