我正在构建一个应用程序,当Firebase实时数据库中的数据发生更改时,我想为用户生成推送通知。我想知道使用Firebase Cloud Messaging是否适合它,并且想了解有关如何使用FCM将数据发送到App的一些想法。
答案 0 :(得分:1)
您需要使用值侦听器来侦听并发送有关数据更改的通知,例如:
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Send notification here
FirebaseFunctions.getInstance()
.getHttpsCallable("sendNotification")
.call(notificationData)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
return null;
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);
在函数中:
exports.sendNotification = functions.https.onCall((data, context) => {
// I am using FCM Topic to send notification to users.
var fcmTopic = data.fcmTopic;
console.log(data);
var payload = {
data:{
MESSAGE_TAG: "NEW_NOTIF",
MESSAGE_TITLE: "Test!",
MESSAGE_TEXT: "Test."
},
topic: fcmTopic
};
var options = {
priority: "high"
};
admin.messaging().send(payload)
.then(() => {
console.log("success");
return null;
})
.catch(error => {
console.log(error);
});
});
更多信息:https://firebase.google.com/docs/database/android/read-and-write#listen_for_value_events
答案 1 :(得分:0)
这是我写的script,用于在此处触发更改时发送通知