首页 > 解决方案 > 如何在firestore android studio中获取新添加数据的通知?

问题描述

我正在我的应用程序上做一个通知,我正在使用 firestore。我的问题是我想在检测到新添加的数据到数据库时向用户发送通知snapshotlistener但是当我打开应用程序时,即使我没有添加新数据,它也会立即显示现有通知。我需要一些条件,我只能获取新添加的数据,或者如果我的数据库数据中缺少某些东西,需要克服这个问题。下面是我的数据库结构。在此处输入图像描述

db.collection("Buyers")
                .document(userID)
                .collection("Notifications")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot snapshots, @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            Log.e(LOG_DB, e.toString());
                            return;
                        }
                        for (DocumentChange dc : snapshots.getDocumentChanges()) {

                            if (dc.getType() == DocumentChange.Type.ADDED) {
                                String title = dc.getDocument().getData().get("notificationTitle").toString();
                                String body = dc.getDocument().getData().get("notificationBody").toString();

                                //Method to set Notifications
                                getNotification(title, body);
                            }
                        }
                    }
                });

标签: javaandroidnotificationsgoogle-cloud-firestoresnapshot

解决方案


如果您只想发送通知,您可以使用 Firebase Cloud Messages,它可能会提供您尝试自己实现的功能。 https://firebase.google.com/docs/cloud-messaging

如果您想在 Firestore 中的数据发生更改后发送通知,您可以使用 FireStore 触发器(https://firebase.google.com/docs/functions/firestore-events)并通过 firebase 函数调用发送通知(发送推送使用 Cloud Functions for Firebase 的通知


推荐阅读