【发布时间】:2017-11-24 05:56:26
【问题描述】:
我需要一个用于 android 的无服务器推送通知的 firebase 云功能示例。
【问题讨论】:
标签: android firebase push-notification firebase-cloud-messaging google-cloud-functions
我需要一个用于 android 的无服务器推送通知的 firebase 云功能示例。
【问题讨论】:
标签: android firebase push-notification firebase-cloud-messaging google-cloud-functions
在您希望触发云功能发送通知的 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);
});
});
});
欲了解更多信息,请查看 - Serverless notifications with Cloud Functions for Firebase
【讨论】: