Firebase Android - 数据库触发器

时间:2017-09-11 18:03:26

标签: android firebase push-notification

我尝试从here开始关注数字10,但我没有配置结算帐户,为什么会这样?

我在这里的功能是,当管理员发布新内容时,所有用户都会收到推送通知,说明有新内容。

// Points to my News ID, new contents posted here will send push notifications to all the users via device token
exports.sendNotifications = functions.database.ref('/Newsv2/{newsID}').onWrite(event => {
    const snapshot = event.data;
    // Only send a notification when a new message has been created.
    if (snapshot.previous.val()) {
        return;
    }
    // Notification details, I modified it for test use first.
    const text = snapshot.val().text;
    const payload = {
        notification: {
            title: "Test Notification",
            body: "",
            icon: "",
            click_action: ""
        }
    };
    // Get the list of device tokens.
    //root/
    //   Usersv2/
    //         userID/
    //             -name
    //             -age
    //             -device_token
    //The above how it'll looks like in the Database
    return admin.database().ref('/Usersv2/{userID}/{device_token}').once('value').then(allTokens => {
        if (allTokens.val()) {
            // Listing all tokens.
            const tokens = Object.keys(allTokens.val());
            // Send notifications to all tokens.
            return admin.messaging().sendToDevice(tokens, payload).then(response => {
                // For each message check if there was an error.
                const tokensToRemove = [];
                response.results.forEach((result, index) => {
                    const error = result.error;
                    if (error) {
                        console.error('Failure sending notification to', tokens[index], error);
                        // Cleanup the tokens who are not registered anymore.
                        if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                            tokensToRemove.push(allTokens.ref.child(tokens[index]).remove());
                        }
                    }
                });
                return Promise.all(tokensToRemove);
            });
        }
    });
});

0 个答案:

没有答案